<?php
session_start();
header('Content-Type: application/json');
require_once __DIR__ . '/../../../database/connection.php';

$db = getDB();
$pdo = $db->getConnection();

try {
    $type = isset($_GET['type']) ? strtolower(trim($_GET['type'])) : 'deposit';
    if (!in_array($type, ['deposit','withdraw'])) $type = 'deposit';
    $ensureSql = "CREATE TABLE IF NOT EXISTS payment_methods (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(64) NOT NULL,
        display_name VARCHAR(128) NOT NULL,
        provider_key VARCHAR(64) NOT NULL,
        category VARCHAR(32) NOT NULL,
        type ENUM('deposit','withdraw','both') NOT NULL DEFAULT 'deposit',
        logo_path VARCHAR(255) NULL,
        config JSON NULL,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
    $pdo->exec($ensureSql);
    

    $seedNeeded = false;
    $stmtCount = $pdo->query("SELECT COUNT(*) FROM payment_methods");
    $hasAny = (int)$stmtCount->fetchColumn() > 0;
    if (!$hasAny) $seedNeeded = true;

    if ($seedNeeded) {
        $ins = $pdo->prepare("INSERT INTO payment_methods (name, display_name, provider_key, category, type, logo_path, config, supported_currencies, is_active) VALUES (?,?,?,?,?, ?, ?, ?,1)");
        $cfg = json_encode(['api' => 'big4pay', 'endpoint' => 'https://api.big4pay.com', 'auth' => ['key' => '']]);
        $ins->execute(['Big4Pay Card', 'Big4Pay (Card)', 'big4pay', 'card', 'deposit', null, $cfg, 'USD']);
        $cfg2 = json_encode(['api' => 'bank_transfer']);
        $ins->execute(['Bank Transfer', 'Transferencia Bancaria', 'bank', 'bank', 'deposit', null, $cfg2, 'USD']);
    }

    $currency = isset($_GET['currency']) ? strtoupper(trim($_GET['currency'])) : '';
    if ($currency !== '') {
        $sel = $pdo->prepare("SELECT id, name, display_name, provider_key, category, type, logo_path, config, supported_currencies, api_group, api_key, api_endpoint, handler_class, min_amount, max_amount, eta_label FROM payment_methods WHERE is_active = 1 AND (type = ? OR type = 'both') AND (supported_currencies IS NULL OR supported_currencies = '' OR supported_currencies LIKE ?) ORDER BY id ASC");
        $like = '%' . $currency . '%';
        $sel->execute([$type, $like]);
    } else {
        $sel = $pdo->prepare("SELECT id, name, display_name, provider_key, category, type, logo_path, config, supported_currencies, api_group, api_key, api_endpoint, handler_class, min_amount, max_amount, eta_label FROM payment_methods WHERE is_active = 1 AND (type = ? OR type = 'both') ORDER BY id ASC");
        $sel->execute([$type]);
    }
    $rows = $sel->fetchAll(PDO::FETCH_ASSOC) ?: [];
    $body = ['success' => true, 'methods' => $rows];
    $etag = 'pm_' . md5(json_encode($body));
    header('ETag: ' . $etag);
    header('Cache-Control: public, max-age=300');
    $ifMatch = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? trim($_SERVER['HTTP_IF_NONE_MATCH']) : '';
    if ($ifMatch === $etag) { http_response_code(304); exit; }
    echo json_encode($body);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
