<?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: active types that admin has enabled for payout processing
    case 'list':
        $rows = db()->query("
            SELECT cmt.slug, cmt.label, cmt.icon, cmt.description
            FROM cashout_method_types cmt
            INNER JOIN admin_payout_settings aps ON aps.method_key = cmt.slug
            WHERE cmt.is_active = 1 AND aps.is_enabled = 1
            ORDER BY cmt.sort_order ASC, cmt.id ASC
        ")->fetchAll();
        echo json_encode(['success'=>true, 'types'=>$rows]);
        break;

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

    // Admin: create
    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'] ?? '')));
        $label= substr(trim($d['label'] ?? ''), 0, 100);
        $icon = substr(trim($d['icon'] ?? '💰'), 0, 10);
        $desc = substr(trim($d['description'] ?? ''), 0, 200);
        $sort = (int)($d['sort_order'] ?? 99);
        $active = (int)(bool)($d['is_active'] ?? 1);
        if (!$slug || !$label) { echo json_encode(['success'=>false,'error'=>'Slug and label required']); exit; }
        try {
            db()->prepare("INSERT INTO cashout_method_types (slug,label,icon,description,is_active,sort_order) VALUES (?,?,?,?,?,?)")
               ->execute([$slug,$label,$icon,$desc,$active,$sort]);
            echo json_encode(['success'=>true,'id'=>db()->lastInsertId()]);
        } catch (Exception $e) {
            echo json_encode(['success'=>false,'error'=>'Slug already exists']);
        }
        break;

    // Admin: update
    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);
        $label= substr(trim($d['label'] ?? ''), 0, 100);
        $icon = substr(trim($d['icon'] ?? '💰'), 0, 10);
        $desc = substr(trim($d['description'] ?? ''), 0, 200);
        $sort = (int)($d['sort_order'] ?? 0);
        $active = (int)(bool)($d['is_active'] ?? 1);
        if (!$id || !$label) { echo json_encode(['success'=>false,'error'=>'ID and label required']); exit; }
        db()->prepare("UPDATE cashout_method_types SET label=?,icon=?,description=?,is_active=?,sort_order=? WHERE id=?")
           ->execute([$label,$icon,$desc,$active,$sort,$id]);
        echo json_encode(['success'=>true]);
        break;

    // Admin: delete
    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 cashout_method_types WHERE id=?")->execute([$id]);
        echo json_encode(['success'=>true]);
        break;

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