<?php
require '../includes/auth_session.php';
require '../includes/db.php';
require '../includes/functions.php';
require '../includes/propay_gateway_helper.php';
require '../includes/akpay_gateway_helper.php';

propay_ensure_schema($conn);
akpay_ensure_schema($conn);
$msg = '';
$msg_type = 'success';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_gateway_settings'])) {
    $propay_merchant = sanitize($conn, $_POST['propay_merchant_code'] ?? '');
    $propay_secret = htmlspecialchars(strip_tags(trim($_POST['propay_secret_code'] ?? '')), ENT_QUOTES, 'UTF-8');
    $propay_enabled = isset($_POST['propay_enabled']) ? 1 : 0;
    $propay_priority = max(1, min(99, intval($_POST['propay_failover_priority'] ?? 1)));

    $akpay_merchant = sanitize($conn, $_POST['akpay_merchant_code'] ?? '');
    $akpay_secret = htmlspecialchars(strip_tags(trim($_POST['akpay_secret_code'] ?? '')), ENT_QUOTES, 'UTF-8');
    $akpay_api_base = htmlspecialchars(strip_tags(trim($_POST['akpay_api_base_url'] ?? '')), ENT_QUOTES, 'UTF-8');
    $akpay_enabled = isset($_POST['akpay_enabled']) ? 1 : 0;
    $akpay_priority = max(1, min(99, intval($_POST['akpay_failover_priority'] ?? 2)));

    $ok1 = propay_save_settings($conn, $propay_merchant, $propay_secret, $propay_enabled);
    $ok2 = akpay_save_settings($conn, $akpay_merchant, $akpay_secret, $akpay_api_base, $akpay_enabled);
    $ok3 = true;
    $stmtPriority = $conn->prepare("UPDATE payment_gateway_settings SET failover_priority=? WHERE provider=?");
    if ($stmtPriority) {
        $provider = 'propay';
        $stmtPriority->bind_param('is', $propay_priority, $provider);
        $ok3 = $stmtPriority->execute() && $ok3;
        $provider = 'akpay';
        $stmtPriority->bind_param('is', $akpay_priority, $provider);
        $ok3 = $stmtPriority->execute() && $ok3;
        $stmtPriority->close();
    } else { $ok3 = false; }
    if ($ok1 && $ok2 && $ok3) {
        $msg = 'Payment gateway settings saved successfully.';
        $msg_type = 'success';
    } else {
        error_log('Payment gateway settings save failed: ' . $conn->error);
        $msg = 'Unable to save the settings right now.';
        $msg_type = 'error';
    }
}

$propay = propay_get_settings($conn);
$akpay = akpay_get_settings($conn);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Gateway Settings</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body class="bg-gray-100 text-slate-800">
    <?php include '../includes/sidebar_admin.php'; ?>

    <main class="lg:ml-64 p-4 lg:p-8 min-h-screen">
        <div class="mb-6">
            <h1 class="text-2xl font-black text-gray-800">Payment Gateway Settings</h1>
        </div>

        <?php if($msg): ?>
            <div class="mb-6 p-4 rounded-xl border-l-4 bg-white shadow-sm <?php echo $msg_type === 'success' ? 'border-green-500 text-green-700' : 'border-red-500 text-red-700'; ?>">
                <i class="fas <?php echo $msg_type === 'success' ? 'fa-check-circle' : 'fa-exclamation-triangle'; ?> mr-2"></i>
                <span class="font-bold text-sm"><?php echo htmlspecialchars($msg, ENT_QUOTES, 'UTF-8'); ?></span>
            </div>
        <?php endif; ?>

        <form method="POST" class="max-w-5xl space-y-6">
            <div class="bg-white rounded-2xl shadow-sm border border-gray-200 p-6">
                <div class="flex items-center justify-between mb-5">
                    <h2 class="font-black text-lg text-gray-800 flex items-center gap-2"><i class="fas fa-key text-emerald-600"></i> ProPay Gateway</h2>
                    <label class="inline-flex items-center gap-2 text-xs font-black uppercase text-gray-500">
                        <input type="checkbox" name="propay_enabled" value="1" <?php echo intval($propay['is_enabled'] ?? 1) === 1 ? 'checked' : ''; ?> class="w-4 h-4">
                        Enabled
                    </label>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                    <div>
                        <label class="block text-xs font-black text-gray-500 uppercase tracking-widest mb-2">Merchant Code</label>
                        <input type="text" name="propay_merchant_code" value="<?php echo htmlspecialchars($propay['merchant_code'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" class="w-full border border-gray-300 rounded-xl px-4 py-3 font-bold focus:outline-none focus:ring-2 focus:ring-emerald-400">
                    </div>
                    <div>
                        <label class="block text-xs font-black text-gray-500 uppercase tracking-widest mb-2">Secret Key</label>
                        <input type="text" name="propay_secret_code" value="<?php echo htmlspecialchars($propay['secret_code'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" class="w-full border border-gray-300 rounded-xl px-4 py-3 font-bold focus:outline-none focus:ring-2 focus:ring-emerald-400">
                    </div>
                    <div>
                        <label class="block text-xs font-black text-gray-500 uppercase tracking-widest mb-2">Withdraw Priority</label>
                        <input type="number" min="1" max="99" name="propay_failover_priority" value="<?php echo intval($propay['failover_priority'] ?? 1); ?>" class="w-full border border-gray-300 rounded-xl px-4 py-3 font-bold focus:outline-none focus:ring-2 focus:ring-emerald-400">
                        <p class="mt-1 text-[11px] text-gray-400">Lower number is tried first for withdrawals.</p>
                    </div>
                    <div class="rounded-xl border bg-gray-50 px-4 py-3">
                        <div class="text-[11px] font-black uppercase tracking-widest text-gray-400">Last Withdraw Health</div>
                        <div class="mt-1 text-sm font-bold text-gray-700"><?php echo htmlspecialchars($propay['last_health_status'] ?: 'Not checked', ENT_QUOTES, 'UTF-8'); ?></div>
                        <?php if (!empty($propay['last_error'])): ?><div class="mt-1 text-xs text-gray-500 break-words"><?php echo htmlspecialchars($propay['last_error'], ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-2xl shadow-sm border border-gray-200 p-6">
                <div class="flex items-center justify-between mb-5">
                    <h2 class="font-black text-lg text-gray-800 flex items-center gap-2"><i class="fas fa-shield-alt text-emerald-600"></i> AKPay Gateway</h2>
                    <label class="inline-flex items-center gap-2 text-xs font-black uppercase text-gray-500">
                        <input type="checkbox" name="akpay_enabled" value="1" <?php echo intval($akpay['is_enabled'] ?? 1) === 1 ? 'checked' : ''; ?> class="w-4 h-4">
                        Enabled
                    </label>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                    <div>
                        <label class="block text-xs font-black text-gray-500 uppercase tracking-widest mb-2">Merchant ID</label>
                        <input type="text" name="akpay_merchant_code" value="<?php echo htmlspecialchars($akpay['merchant_code'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" class="w-full border border-gray-300 rounded-xl px-4 py-3 font-bold focus:outline-none focus:ring-2 focus:ring-emerald-400">
                    </div>
                    <div>
                        <label class="block text-xs font-black text-gray-500 uppercase tracking-widest mb-2">Secret Key</label>
                        <input type="text" name="akpay_secret_code" value="<?php echo htmlspecialchars($akpay['secret_code'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" class="w-full border border-gray-300 rounded-xl px-4 py-3 font-bold focus:outline-none focus:ring-2 focus:ring-emerald-400">
                    </div>
                    <div>
                        <label class="block text-xs font-black text-gray-500 uppercase tracking-widest mb-2">Withdraw Priority</label>
                        <input type="number" min="1" max="99" name="akpay_failover_priority" value="<?php echo intval($akpay['failover_priority'] ?? 2); ?>" class="w-full border border-gray-300 rounded-xl px-4 py-3 font-bold focus:outline-none focus:ring-2 focus:ring-emerald-400">
                        <p class="mt-1 text-[11px] text-gray-400">Lower number is tried first for withdrawals.</p>
                    </div>
                    <div class="rounded-xl border bg-gray-50 px-4 py-3">
                        <div class="text-[11px] font-black uppercase tracking-widest text-gray-400">Last Withdraw Health</div>
                        <div class="mt-1 text-sm font-bold text-gray-700"><?php echo htmlspecialchars($akpay['last_health_status'] ?: 'Not checked', ENT_QUOTES, 'UTF-8'); ?></div>
                        <?php if (!empty($akpay['last_error'])): ?><div class="mt-1 text-xs text-gray-500 break-words"><?php echo htmlspecialchars($akpay['last_error'], ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
                    </div>
                    <div class="md:col-span-2">
                        <label class="block text-xs font-black text-gray-500 uppercase tracking-widest mb-2">API Base URL</label>
                        <input type="text" name="akpay_api_base_url" value="<?php echo htmlspecialchars($akpay['api_base_url'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" class="w-full border border-gray-300 rounded-xl px-4 py-3 font-bold focus:outline-none focus:ring-2 focus:ring-emerald-400">
                    </div>
                </div>
            </div>

            <button type="submit" name="save_gateway_settings" class="bg-[#126E51] hover:bg-[#0d4a3a] text-white px-6 py-3 rounded-xl font-black shadow-md">
                <i class="fas fa-save mr-2"></i> Save Settings
            </button>
        </form>
    </main>
</body>
</html>
