<?php
ob_start();
try { require_once __DIR__ . '/../../includes/auth.php'; } catch(Throwable $e) { ob_end_clean(); header('Content-Type: application/json'); echo json_encode(['success'=>false,'error'=>'Server error']); exit; }
ob_end_clean();
header('Content-Type: application/json');

$action        = $_GET['action'] ?? 'list';
$isAdmin       = isLoggedIn() && !empty($_SESSION['is_admin']);
$isMasterAdmin = $isAdmin && (int)($_SESSION['user_id'] ?? 0) === MASTER_ADMIN_ID;

switch ($action) {

    // ── Public: active platforms for player app ───────────
    case 'list':
        $stmt = db()->query("SELECT slug,name,player_url,url_alias_param,color,icon_path FROM platforms WHERE is_active=1 AND is_deleted=0 ORDER BY sort_order ASC, id ASC");
        $rows = $stmt->fetchAll();
        $out = array_map(fn($r) => [
            'id'          => $r['slug'],
            'name'        => $r['name'],
            'url'         => $r['player_url'],
            'alias_param' => $r['url_alias_param'] ?? '',
            'color'       => $r['color'],
        ], $rows);
        echo json_encode(['success'=>true, 'platforms'=>$out]);
        break;

    // ── Admin: full list including agent fields and inactive ─
    case 'admin_list':
        if (!$isAdmin) { echo json_encode(['success'=>false,'error'=>'Forbidden']); exit; }
        $rows = db()->query("SELECT * FROM platforms WHERE is_deleted=0 ORDER BY sort_order ASC, id ASC")->fetchAll();
        echo json_encode(['success'=>true, 'platforms'=>$rows]);
        break;

    // ── Admin: create platform ────────────────────────────
    case 'create':
        if (!$isAdmin || $_SERVER['REQUEST_METHOD'] !== 'POST') { echo json_encode(['success'=>false,'error'=>'Forbidden']); exit; }
        $d = json_decode(file_get_contents('php://input'), true);
        $slug            = preg_replace('/[^a-z0-9_]/', '', strtolower(trim($d['slug'] ?? '')));
        $name            = substr(trim($d['name']           ?? ''), 0, 100);
        $player_url      = substr(trim($d['player_url']     ?? ''), 0, 500);
        $url_alias_param = preg_replace('/[^a-zA-Z0-9_\-]/', '', trim($d['url_alias_param'] ?? ''));
        $agent_link      = substr(trim($d['agent_link']     ?? ''), 0, 500);
        $agent_login     = substr(trim($d['agent_login']    ?? ''), 0, 200);
        $agent_password  = substr(trim($d['agent_password'] ?? ''), 0, 200);
        $games_link      = substr(trim($d['games_link']     ?? ''), 0, 500);
        $agent_guide        = trim($d['agent_guide'] ?? '');
        $sub_agent_login    = substr(trim($d['sub_agent_login']    ?? ''), 0, 200);
        $sub_agent_password = substr(trim($d['sub_agent_password'] ?? ''), 0, 200);
        $cashier_login      = substr(trim($d['cashier_login']      ?? ''), 0, 200);
        $cashier_password   = substr(trim($d['cashier_password']   ?? ''), 0, 200);
        $color           = preg_match('/^#[0-9a-fA-F]{3,8}$/', $d['color'] ?? '') ? $d['color'] : '#f0c040';
        $sort_order      = (int)($d['sort_order'] ?? 99);
        $is_active       = isset($d['is_active']) ? (int)(bool)$d['is_active'] : 1;
        if (!$slug || !$name || !$player_url) { echo json_encode(['success'=>false,'error'=>'Slug, name, and player URL are required']); exit; }
        try {
            $stmt = db()->prepare("INSERT INTO platforms (slug,name,player_url,url_alias_param,agent_link,agent_login,agent_password,games_link,agent_guide,sub_agent_login,sub_agent_password,cashier_login,cashier_password,color,sort_order,is_active) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            $stmt->execute([$slug,$name,$player_url,$url_alias_param,$agent_link,$agent_login,$agent_password,$games_link,$agent_guide,$sub_agent_login,$sub_agent_password,$cashier_login,$cashier_password,$color,$sort_order,$is_active]);
            echo json_encode(['success'=>true,'id'=>db()->lastInsertId()]);
        } catch (Exception $e) {
            echo json_encode(['success'=>false,'error'=>'Slug already exists or DB error']);
        }
        break;

    // ── Admin: update platform ────────────────────────────
    case 'update':
        if (!$isAdmin || $_SERVER['REQUEST_METHOD'] !== 'POST') { echo json_encode(['success'=>false,'error'=>'Forbidden']); exit; }
        $d = json_decode(file_get_contents('php://input'), true);
        $id              = (int)($d['id'] ?? 0);
        $name            = substr(trim($d['name']           ?? ''), 0, 100);
        $player_url      = substr(trim($d['player_url']     ?? ''), 0, 500);
        $url_alias_param = preg_replace('/[^a-zA-Z0-9_\-]/', '', trim($d['url_alias_param'] ?? ''));
        $agent_link      = substr(trim($d['agent_link']     ?? ''), 0, 500);
        $agent_login     = substr(trim($d['agent_login']    ?? ''), 0, 200);
        $agent_password  = substr(trim($d['agent_password'] ?? ''), 0, 200);
        $games_link      = substr(trim($d['games_link']     ?? ''), 0, 500);
        $agent_guide        = trim($d['agent_guide'] ?? '');
        $sub_agent_login    = substr(trim($d['sub_agent_login']    ?? ''), 0, 200);
        $sub_agent_password = substr(trim($d['sub_agent_password'] ?? ''), 0, 200);
        $cashier_login      = substr(trim($d['cashier_login']      ?? ''), 0, 200);
        $cashier_password   = substr(trim($d['cashier_password']   ?? ''), 0, 200);
        $color           = preg_match('/^#[0-9a-fA-F]{3,8}$/', $d['color'] ?? '') ? $d['color'] : '#f0c040';
        $sort_order      = (int)($d['sort_order'] ?? 99);
        $is_active       = (int)(bool)($d['is_active'] ?? 1);
        if (!$id || !$name || !$player_url) { echo json_encode(['success'=>false,'error'=>'ID, name, and player URL required']); exit; }
        if ($isMasterAdmin) {
            // Master admin: update all fields including agent info
            db()->prepare("UPDATE platforms SET name=?,player_url=?,url_alias_param=?,agent_link=?,agent_login=?,agent_password=?,games_link=?,agent_guide=?,sub_agent_login=?,sub_agent_password=?,cashier_login=?,cashier_password=?,color=?,sort_order=?,is_active=? WHERE id=?")
                 ->execute([$name,$player_url,$url_alias_param,$agent_link,$agent_login,$agent_password,$games_link,$agent_guide,$sub_agent_login,$sub_agent_password,$cashier_login,$cashier_password,$color,$sort_order,$is_active,$id]);
        } else {
            // Regular admin: update non-sensitive fields including alias param
            db()->prepare("UPDATE platforms SET name=?,player_url=?,url_alias_param=?,color=?,sort_order=?,is_active=? WHERE id=?")
                 ->execute([$name,$player_url,$url_alias_param,$color,$sort_order,$is_active,$id]);
        }
        echo json_encode(['success'=>true]);
        break;

    // ── Admin: delete platform ────────────────────────────
    case 'delete':
        if (!$isAdmin || $_SERVER['REQUEST_METHOD'] !== 'POST') { echo json_encode(['success'=>false,'error'=>'Forbidden']); exit; }
        $d = json_decode(file_get_contents('php://input'), true);
        $id = (int)($d['id'] ?? 0);
        if (!$id) { echo json_encode(['success'=>false,'error'=>'ID required']); exit; }
        db()->prepare("DELETE FROM platforms WHERE id=?")->execute([$id]);
        echo json_encode(['success'=>true]);
        break;

    // ── Admin: reorder platforms ──────────────────────────
    case 'reorder':
        if (!$isAdmin || $_SERVER['REQUEST_METHOD'] !== 'POST') { echo json_encode(['success'=>false,'error'=>'Forbidden']); exit; }
        $d = json_decode(file_get_contents('php://input'), true);
        $order = $d['order'] ?? []; // array of IDs in desired order
        $stmt = db()->prepare("UPDATE platforms SET sort_order=? WHERE id=?");
        foreach ($order as $i => $pid) { $stmt->execute([$i, (int)$pid]); }
        echo json_encode(['success'=>true]);
        break;

    // ── Admin: list credits for a platform ───────────────
    case 'credits_list':
        if (!$isAdmin) { echo json_encode(['success'=>false,'error'=>'Forbidden']); exit; }
        $pid = (int)($_GET['platform_id'] ?? 0);
        if (!$pid) { echo json_encode(['success'=>false,'error'=>'platform_id required']); exit; }
        $rows = db()->prepare("SELECT * FROM platform_credits WHERE platform_id=? ORDER BY credit_date DESC, id DESC");
        $rows->execute([$pid]);
        $credits = $rows->fetchAll();
        $total = db()->prepare("SELECT COALESCE(SUM(CASE WHEN type='debit' THEN -credits_purchased ELSE credits_purchased END),0) FROM platform_credits WHERE platform_id=?");
        $total->execute([$pid]);
        echo json_encode(['success'=>true,'credits'=>$credits,'total'=>(float)$total->fetchColumn()]);
        break;

    // ── Admin: add credit entry ───────────────────────────
    case 'credits_create':
        if (!$isMasterAdmin || $_SERVER['REQUEST_METHOD'] !== 'POST') { echo json_encode(['success'=>false,'error'=>'Forbidden']); exit; }
        $d = json_decode(file_get_contents('php://input'), true);
        $pid     = (int)($d['platform_id'] ?? 0);
        $credits = (float)($d['credits_purchased'] ?? 0);
        $date    = $d['credit_date'] ?? date('Y-m-d');
        $method  = substr(trim($d['payment_method'] ?? ''), 0, 100);
        $notes   = trim($d['notes'] ?? '');
        if (!$pid || $credits <= 0 || !$date) { echo json_encode(['success'=>false,'error'=>'platform_id, credits_purchased, and credit_date are required']); exit; }
        $stmt = db()->prepare("INSERT INTO platform_credits (platform_id,credits_purchased,credit_date,payment_method,notes) VALUES (?,?,?,?,?)");
        $stmt->execute([$pid,$credits,$date,$method,$notes]);
        $newId = db()->lastInsertId();
        $total = db()->prepare("SELECT COALESCE(SUM(credits_purchased),0) FROM platform_credits WHERE platform_id=?");
        $total->execute([$pid]);
        echo json_encode(['success'=>true,'id'=>$newId,'total'=>(float)$total->fetchColumn()]);
        break;

    // ── Admin: update credit entry ────────────────────────
    case 'credits_update':
        if (!$isMasterAdmin || $_SERVER['REQUEST_METHOD'] !== 'POST') { echo json_encode(['success'=>false,'error'=>'Forbidden']); exit; }
        $d = json_decode(file_get_contents('php://input'), true);
        $id      = (int)($d['id'] ?? 0);
        $credits = (float)($d['credits_purchased'] ?? 0);
        $date    = $d['credit_date'] ?? date('Y-m-d');
        $method  = substr(trim($d['payment_method'] ?? ''), 0, 100);
        $notes   = trim($d['notes'] ?? '');
        if (!$id || $credits <= 0 || !$date) { echo json_encode(['success'=>false,'error'=>'id, credits_purchased, and credit_date are required']); exit; }
        db()->prepare("UPDATE platform_credits SET credits_purchased=?,credit_date=?,payment_method=?,notes=? WHERE id=?")
             ->execute([$credits,$date,$method,$notes,$id]);
        $row = db()->prepare("SELECT platform_id FROM platform_credits WHERE id=?");
        $row->execute([$id]);
        $pid = (int)($row->fetchColumn() ?: 0);
        $total = db()->prepare("SELECT COALESCE(SUM(credits_purchased),0) FROM platform_credits WHERE platform_id=?");
        $total->execute([$pid]);
        echo json_encode(['success'=>true,'total'=>(float)$total->fetchColumn()]);
        break;

    // ── Admin: delete credit entry ────────────────────────
    case 'credits_delete':
        if (!$isMasterAdmin || $_SERVER['REQUEST_METHOD'] !== 'POST') { echo json_encode(['success'=>false,'error'=>'Forbidden']); exit; }
        $d = json_decode(file_get_contents('php://input'), true);
        $id = (int)($d['id'] ?? 0);
        if (!$id) { echo json_encode(['success'=>false,'error'=>'ID required']); exit; }
        $row = db()->prepare("SELECT platform_id FROM platform_credits WHERE id=?");
        $row->execute([$id]);
        $pid = (int)($row->fetchColumn() ?: 0);
        db()->prepare("DELETE FROM platform_credits WHERE id=?")->execute([$id]);
        $total = db()->prepare("SELECT COALESCE(SUM(credits_purchased),0) FROM platform_credits WHERE platform_id=?");
        $total->execute([$pid]);
        echo json_encode(['success'=>true,'total'=>(float)$total->fetchColumn()]);
        break;

    default:
        echo json_encode(['success'=>false,'error'=>'Unknown action']);
}
