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

switch ($action) {

    // Public: get all enabled payment methods including card status
    case 'list':
        // Include card row (is_enabled controls whether card appears at checkout)
        $rows = db()->query("SELECT method_key, label, handle, instructions, is_enabled FROM payment_settings ORDER BY sort_order ASC, id ASC")->fetchAll();
        echo json_encode(['success'=>true, 'methods'=>$rows]);
        break;

    // Admin: get all methods including disabled
    case 'admin_list':
        if (!$isAdmin) { echo json_encode(['success'=>false,'error'=>'Forbidden']); exit; }
        $rows = db()->query("SELECT * FROM payment_settings ORDER BY sort_order ASC, id ASC")->fetchAll();
        echo json_encode(['success'=>true, 'methods'=>$rows]);
        break;

    // Admin: update a single method
    case 'update':
        if (!$isAdmin || $_SERVER['REQUEST_METHOD'] !== 'POST') { echo json_encode(['success'=>false]); exit; }
        $d    = json_decode(file_get_contents('php://input'), true);
        $id   = (int)($d['id'] ?? 0);
        $label= substr(trim($d['label']??''), 0, 100);
        $handle = substr(trim($d['handle']??''), 0, 200);
        $instructions = substr(trim($d['instructions']??''), 0, 500);
        $enabled = (int)(bool)($d['is_enabled'] ?? 1);
        $sort  = (int)($d['sort_order'] ?? 0);
        if (!$id) { echo json_encode(['success'=>false,'error'=>'ID required']); exit; }
        db()->prepare("UPDATE payment_settings SET label=?,handle=?,instructions=?,is_enabled=?,sort_order=? WHERE id=?")
             ->execute([$label,$handle,$instructions,$enabled,$sort,$id]);
        echo json_encode(['success'=>true]);
        break;

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