<?php

header('Content-Type: application/json');
$response = ['success' => false, 'methods' => [], 'message' => 'Gagal memuat metode deposit.'];

require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/session.php';
require_once __DIR__ . '/../../lib/Auth.php';
require_once __DIR__ . '/../../includes/functions.php';
if (!Auth::isLoggedIn()) { http_response_code(401); $response['message'] = 'Sesi berakhir.'; echo json_encode($response); exit; }

if (!isset($pdo) || !$pdo instanceof PDO) { http_response_code(500); error_log("PDO object not available in get_deposit_methods.php"); $response['message'] = 'Koneksi database gagal.'; echo json_encode($response); exit; }

try {
    $filterType = $_GET['type'] ?? 'all';

    $sql = "SELECT id, name, code, type, logo_url, min_deposit, max_deposit, bonus_percentage, rate, instructions, is_auto_check
            FROM deposit_methods
            WHERE status = 'active'";

    $params = [];
    if ($filterType !== 'all') {
        $sql .= " AND type = :type";
        $params[':type'] = $filterType;
    }

    $sql .= " ORDER BY type ASC, name ASC";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $methods = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $response['success'] = true;
    $response['methods'] = $methods;
    unset($response['message']);

} catch (\PDOException $e) {
    error_log("AJAX Get Deposit Methods DB Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan database saat memuat metode deposit.";
    http_response_code(500);
} catch (\Throwable $e) {
    error_log("AJAX Get Deposit Methods General Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan internal server.";
    if (defined('DEBUG_MODE') && DEBUG_MODE === true) { $response['debug_php'] = $e->getMessage(); }
    http_response_code(500);
}

echo json_encode($response);
exit;
?>
