<?php
ob_start();
require_once __DIR__ . '/../../includes/auth.php';
ob_end_clean();
header('Content-Type: application/json');
if (!isLoggedIn()) { echo json_encode(['success'=>false,'error'=>'Not authenticated']); exit; }
$userId  = (int)$_SESSION['user_id'];
$isAdmin = !empty($_SESSION['is_admin']);
$method  = $_SERVER['REQUEST_METHOD'];
$action  = $_GET['action'] ?? 'list';

if ($method === 'GET') {
    if ($action === 'list') {
        $uid = $isAdmin ? (int)($_GET['user_id'] ?? $userId) : $userId;
        $stmt = db()->prepare("SELECT pa.*, COALESCE(p.name, pa.platform_slug) AS platform_name, p.color
            FROM platform_accounts pa LEFT JOIN platforms p ON pa.platform_slug=p.slug
            WHERE pa.user_id=? ORDER BY pa.requested_at DESC");
        $stmt->execute([$uid]);
        $rows = $stmt->fetchAll();
        foreach ($rows as &$row) {
            if (!$isAdmin && $row['status'] !== 'approved') $row['platform_password'] = null;
        }
        echo json_encode(['success'=>true,'accounts'=>$rows]);
    } elseif ($action === 'check_onboarding') {
        $cnt = db()->prepare("SELECT COUNT(*) FROM platform_accounts WHERE user_id=?");
        $cnt->execute([$userId]);
        $hasAny = (int)$cnt->fetchColumn() > 0;
        // Check flag — graceful fallback if column doesn't exist
        $done = false;
        try {
            $s = db()->prepare("SELECT platform_onboarding_done FROM users WHERE id=?");
            $s->execute([$userId]);
            $r = $s->fetch(); $done = !empty($r['platform_onboarding_done']);
        } catch(Exception $e){}
        echo json_encode(['success'=>true,'needs_onboarding'=>(!$done && !$hasAny),'has_accounts'=>$hasAny]);
    } else {
        echo json_encode(['success'=>false,'error'=>'Unknown action']);
    }
    exit;
}

if ($method !== 'POST') { echo json_encode(['success'=>false,'error'=>'Method not allowed']); exit; }
$d = json_decode(file_get_contents('php://input'), true);

if ($action === 'request') {
    $slug = preg_replace('/[^a-z0-9_]/','',strtolower(trim($d['platform_slug']??'')));
    if (!$slug) { echo json_encode(['success'=>false,'error'=>'Platform required']); exit; }
    try {
        db()->prepare("INSERT INTO platform_accounts (user_id,platform_slug) VALUES (?,?)")->execute([$userId,$slug]);
        try { db()->prepare("UPDATE users SET platform_onboarding_done=1 WHERE id=?")->execute([$userId]); } catch(Exception $e){}
        echo json_encode(['success'=>true]);
    } catch(Exception $e) { echo json_encode(['success'=>false,'error'=>'Already requested for this platform']); }
    exit;
}
if ($action === 'dismiss_onboarding') {
    try { db()->prepare("UPDATE users SET platform_onboarding_done=1 WHERE id=?")->execute([$userId]); } catch(Exception $e){}
    echo json_encode(['success'=>true]);
    exit;
}
if (!$isAdmin) { echo json_encode(['success'=>false,'error'=>'Forbidden']); exit; }
if ($action === 'resolve') {
    $id=$d['id']??0; $status=$d['status']??'';
    $uname=substr(trim($d['platform_username']??''),0,100);
    $pass=substr(trim($d['platform_password']??''),0,200);
    $note=substr(trim($d['admin_note']??''),0,300);
    if (!in_array($status,['approved','denied','deleted'])){echo json_encode(['success'=>false,'error'=>'Invalid status']);exit;}
    $chk=db()->prepare("SELECT user_id,platform_slug FROM platform_accounts WHERE id=?");$chk->execute([$id]);$row=$chk->fetch();
    if (!$row){echo json_encode(['success'=>false,'error'=>'Not found']);exit;}
    db()->prepare("UPDATE platform_accounts SET status=?,platform_username=?,platform_password=?,admin_note=?,resolved_at=NOW(),admin_id=? WHERE id=?")
       ->execute([$status,$uname,$pass,$note,(int)$_SESSION['user_id'],$id]);
    if ($status==='approved'&&$uname) {
        db()->prepare("INSERT INTO game_aliases (user_id,platform_slug,alias) VALUES (?,?,?) ON DUPLICATE KEY UPDATE alias=VALUES(alias)")
           ->execute([$row['user_id'],$row['platform_slug'],$uname]);
    }
    echo json_encode(['success'=>true]);exit;
}
if ($action === 'update_credentials') {
    $id=$d['id']??0;
    $uname=substr(trim($d['platform_username']??''),0,100);
    $pass=substr(trim($d['platform_password']??''),0,200);
    $note=substr(trim($d['admin_note']??''),0,300);
    $chk=db()->prepare("SELECT user_id,platform_slug FROM platform_accounts WHERE id=?");$chk->execute([$id]);$row=$chk->fetch();
    if (!$row){echo json_encode(['success'=>false,'error'=>'Not found']);exit;}
    db()->prepare("UPDATE platform_accounts SET platform_username=?,platform_password=?,admin_note=? WHERE id=?")
       ->execute([$uname,$pass,$note,$id]);
    if ($uname) {
        db()->prepare("INSERT INTO game_aliases (user_id,platform_slug,alias) VALUES (?,?,?) ON DUPLICATE KEY UPDATE alias=VALUES(alias)")
           ->execute([$row['user_id'],$row['platform_slug'],$uname]);
    }
    echo json_encode(['success'=>true]);exit;
}
echo json_encode(['success'=>false,'error'=>'Unknown action']);
