<?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');

if (!isLoggedIn()) { echo json_encode(['success'=>false,'error'=>'Not authenticated']); exit; }

$action  = $_GET['action'] ?? '';
$userId  = (int)$_SESSION['user_id'];
$isAdmin = !empty($_SESSION['is_admin']);

switch ($action) {

    case 'list':
        $uid = $isAdmin ? (int)($_GET['user_id'] ?? $userId) : $userId;
        $rows = db()->prepare("
            SELECT pm.*,
                   COALESCE(aps.is_enabled, 0) AS admin_enabled
            FROM payout_methods pm
            LEFT JOIN admin_payout_settings aps ON aps.method_key = pm.method_type
            WHERE pm.user_id = ?
            ORDER BY pm.is_default DESC, pm.id ASC
        ");
        $rows->execute([$uid]);
        echo json_encode(['success'=>true, 'methods'=>$rows->fetchAll()]);
        break;

    case 'add':
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') { echo json_encode(['success'=>false]); exit; }
        $d = json_decode(file_get_contents('php://input'), true);
        $uid   = $isAdmin && isset($d['user_id']) ? (int)$d['user_id'] : $userId;
        $type  = preg_replace('/[^a-z0-9_]/', '', strtolower(trim($d['method_type'] ?? '')));
        $label = substr(trim($d['label'] ?? ''), 0, 100);
        $handle= substr(trim($d['account_handle'] ?? ''), 0, 200);
        $def   = (int)(bool)($d['is_default'] ?? 0);
        if (!$type || !$label || !$handle) { echo json_encode(['success'=>false,'error'=>'All fields required']); exit; }
        db()->beginTransaction();
        if ($def) db()->prepare("UPDATE payout_methods SET is_default=0 WHERE user_id=?")->execute([$uid]);
        // If first method, auto-set as default
        $count = db()->prepare("SELECT COUNT(*) FROM payout_methods WHERE user_id=?"); $count->execute([$uid]);
        if ((int)$count->fetchColumn() === 0) $def = 1;
        db()->prepare("INSERT INTO payout_methods (user_id,method_type,label,account_handle,is_default) VALUES (?,?,?,?,?)")
           ->execute([$uid,$type,$label,$handle,$def]);
        $newId = db()->lastInsertId();
        db()->commit();
        echo json_encode(['success'=>true,'id'=>$newId]);
        break;

    case 'set_default':
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') { echo json_encode(['success'=>false]); exit; }
        $d  = json_decode(file_get_contents('php://input'), true);
        $id = (int)($d['id'] ?? 0);
        // Verify ownership
        $chk = db()->prepare("SELECT user_id FROM payout_methods WHERE id=?"); $chk->execute([$id]);
        $row = $chk->fetch();
        if (!$row || ($row['user_id'] != $userId && !$isAdmin)) { echo json_encode(['success'=>false,'error'=>'Not found']); exit; }
        $uid = $row['user_id'];
        db()->prepare("UPDATE payout_methods SET is_default=0 WHERE user_id=?")->execute([$uid]);
        db()->prepare("UPDATE payout_methods SET is_default=1 WHERE id=?")->execute([$id]);
        echo json_encode(['success'=>true]);
        break;

    case 'delete':
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') { echo json_encode(['success'=>false]); exit; }
        $d  = json_decode(file_get_contents('php://input'), true);
        $id = (int)($d['id'] ?? 0);
        $chk = db()->prepare("SELECT user_id,is_default FROM payout_methods WHERE id=?"); $chk->execute([$id]);
        $row = $chk->fetch();
        if (!$row || ($row['user_id'] != $userId && !$isAdmin)) { echo json_encode(['success'=>false,'error'=>'Not found']); exit; }
        db()->prepare("DELETE FROM payout_methods WHERE id=?")->execute([$id]);
        // If deleted default, set next one as default
        if ($row['is_default']) {
            $next = db()->prepare("SELECT id FROM payout_methods WHERE user_id=? LIMIT 1"); $next->execute([$row['user_id']]);
            if ($n = $next->fetch()) db()->prepare("UPDATE payout_methods SET is_default=1 WHERE id=?")->execute([$n['id']]);
        }
        echo json_encode(['success'=>true]);
        break;

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