<?php
session_start();
require_once '../config/database.php';

if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: ../login.php');
    exit();
}

$message = '';
$message_type = '';

// Handle form save
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $pdo->beginTransaction();
        $settings = [
            'zinipay_enabled'     => isset($_POST['zinipay_enabled']) ? '1' : '0',
            'zinipay_api_key'     => trim($_POST['zinipay_api_key'] ?? ''),
            'zinipay_mode'        => $_POST['zinipay_mode'] === 'live' ? 'live' : 'sandbox',
            'zinipay_label'       => trim($_POST['zinipay_label'] ?? 'ZiniPay (bKash/Nagad/Card)'),
        ];
        foreach ($settings as $key => $value) {
            $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value, created_at)
                VALUES (?, ?, NOW()) ON DUPLICATE KEY UPDATE setting_value=?, updated_at=NOW()");
            $stmt->execute([$key, $value, $value]);
        }
        $pdo->commit();
        $message = 'সেটিংস সফলভাবে সংরক্ষিত হয়েছে।';
        $message_type = 'success';
    } catch (Exception $e) {
        $pdo->rollBack();
        $message = 'ত্রুটি: ' . $e->getMessage();
        $message_type = 'danger';
    }
}

// Load current settings
$defaults = [
    'zinipay_enabled' => '0',
    'zinipay_api_key' => '',
    'zinipay_mode'    => 'sandbox',
    'zinipay_label'   => 'ZiniPay (bKash/Nagad/Card)',
];
$s = $pdo->query("SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE 'zinipay_%'");
while ($row = $s->fetch()) {
    $defaults[$row['setting_key']] = $row['setting_value'];
}

// Test connection
$test_result = null;
if (isset($_POST['test_connection']) && !empty($defaults['zinipay_api_key'])) {
    $ch = curl_init('https://api.zinipay.com/v1/payment/create');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode(['test' => true]),
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json',
            'zini-api-key: ' . $defaults['zinipay_api_key'],
        ],
        CURLOPT_TIMEOUT => 8,
    ]);
    $resp = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    // 401 = wrong key, 422/400 = key valid but bad payload — both mean API reachable
    $test_result = ($code === 401)
        ? ['ok' => false, 'msg' => 'API Key সঠিক নয় (401 Unauthorized)']
        : ($code === 0
            ? ['ok' => false, 'msg' => 'API সার্ভারে পৌঁছানো যায়নি']
            : ['ok' => true,  'msg' => 'API Key সঠিক এবং সংযোগ সফল ✓']);
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ZiniPay সেটিংস</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@400;600;700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Hind Siliguri', sans-serif; background: #f4f7f6; }
        .page-header { background: linear-gradient(135deg,#e91e8c,#ff6b35); color:#fff; padding:28px 30px; border-radius:12px; margin-bottom:24px; }
        .settings-card { border:none; border-radius:12px; box-shadow:0 2px 16px rgba(0,0,0,0.08); }
        .section-title { font-size:.7rem; text-transform:uppercase; letter-spacing:.08em; color:#888; font-weight:700; margin-bottom:12px; }
        .api-key-wrap { position:relative; }
        .api-key-wrap input { padding-right:44px; font-family:monospace; }
        .toggle-key { position:absolute; right:10px; top:50%; transform:translateY(-50%); background:none; border:none; color:#888; cursor:pointer; }
        .status-badge { display:inline-flex; align-items:center; gap:6px; padding:6px 14px; border-radius:20px; font-size:.82rem; font-weight:600; }
        .status-on  { background:#d4edda; color:#155724; }
        .status-off { background:#f8d7da; color:#721c24; }
        .mode-badge-live    { background:#fff3cd; color:#856404; }
        .mode-badge-sandbox { background:#cce5ff; color:#004085; }
        .info-box { background:#f8f9fa; border-left:4px solid #e91e8c; border-radius:0 8px 8px 0; padding:14px 16px; font-size:.85rem; }
        .btn-zinipay { background:linear-gradient(135deg,#e91e8c,#ff6b35); border:none; color:#fff; font-weight:600; }
        .btn-zinipay:hover { opacity:.9; color:#fff; }
        .flow-step { display:flex; align-items:flex-start; gap:12px; margin-bottom:12px; }
        .flow-num { background:linear-gradient(135deg,#e91e8c,#ff6b35); color:#fff; border-radius:50%; width:26px; height:26px; display:flex; align-items:center; justify-content:center; font-size:.8rem; font-weight:700; flex-shrink:0; margin-top:2px; }
    </style>
</head>
<body>
<nav class="navbar navbar-dark" style="background:linear-gradient(135deg,#e91e8c,#ff6b35);">
    <div class="container-fluid">
        <span class="navbar-brand"><i class="fas fa-mobile-alt"></i> ZiniPay সেটিংস</span>
        <a href="../index.php" class="btn btn-sm btn-light"><i class="fas fa-arrow-left"></i> ড্যাশবোর্ড</a>
    </div>
</nav>

<div class="container mt-4" style="max-width:760px;">

    <?php if ($message): ?>
        <div class="alert alert-<?= $message_type ?> alert-dismissible fade show">
            <?= htmlspecialchars($message) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <?php if ($test_result !== null): ?>
        <div class="alert alert-<?= $test_result['ok'] ? 'success' : 'danger' ?> alert-dismissible fade show">
            <i class="fas fa-<?= $test_result['ok'] ? 'check-circle' : 'times-circle' ?>"></i>
            <?= htmlspecialchars($test_result['msg']) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- Status bar -->
    <div class="d-flex align-items-center gap-3 mb-3">
        <span class="status-badge <?= $defaults['zinipay_enabled'] === '1' ? 'status-on' : 'status-off' ?>">
            <i class="fas fa-circle" style="font-size:.5rem;"></i>
            <?= $defaults['zinipay_enabled'] === '1' ? 'সক্রিয়' : 'নিষ্ক্রিয়' ?>
        </span>
        <span class="status-badge <?= $defaults['zinipay_mode'] === 'live' ? 'mode-badge-live' : 'mode-badge-sandbox' ?>">
            <i class="fas fa-<?= $defaults['zinipay_mode'] === 'live' ? 'globe' : 'flask' ?>"></i>
            <?= $defaults['zinipay_mode'] === 'live' ? 'Live Mode' : 'Sandbox Mode' ?>
        </span>
    </div>

    <form method="POST">
        <div class="card settings-card mb-4">
            <div class="card-body p-4">
                <div class="section-title">মূল সেটিংস</div>

                <!-- Enable toggle -->
                <div class="d-flex justify-content-between align-items-center mb-3 p-3 bg-light rounded">
                    <div>
                        <div class="fw-bold">ZiniPay পেমেন্ট সক্রিয় করুন</div>
                        <small class="text-muted">শিক্ষার্থীরা ZiniPay দিয়ে ফি পরিশোধ করতে পারবে</small>
                    </div>
                    <div class="form-check form-switch mb-0">
                        <input class="form-check-input" type="checkbox" role="switch"
                               id="zinipay_enabled" name="zinipay_enabled" style="width:3rem;height:1.5rem;"
                               <?= $defaults['zinipay_enabled'] === '1' ? 'checked' : '' ?>>
                    </div>
                </div>

                <!-- Mode -->
                <div class="mb-3">
                    <label class="form-label fw-bold">মোড</label>
                    <div class="d-flex gap-3">
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="zinipay_mode" id="mode_sandbox" value="sandbox"
                                   <?= $defaults['zinipay_mode'] !== 'live' ? 'checked' : '' ?>>
                            <label class="form-check-label" for="mode_sandbox">
                                <i class="fas fa-flask text-primary"></i> Sandbox (টেস্ট)
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="zinipay_mode" id="mode_live" value="live"
                                   <?= $defaults['zinipay_mode'] === 'live' ? 'checked' : '' ?>>
                            <label class="form-check-label" for="mode_live">
                                <i class="fas fa-globe text-success"></i> Live (প্রকৃত পেমেন্ট)
                            </label>
                        </div>
                    </div>
                </div>

                <!-- API Key -->
                <div class="mb-3">
                    <label class="form-label fw-bold">API Key (Brand Key)</label>
                    <div class="api-key-wrap">
                        <input type="password" class="form-control" id="zinipay_api_key" name="zinipay_api_key"
                               value="<?= htmlspecialchars($defaults['zinipay_api_key']) ?>"
                               placeholder="আপনার ZiniPay Brand Key এখানে দিন">
                        <button type="button" class="toggle-key" onclick="toggleKey()">
                            <i class="fas fa-eye" id="keyIcon"></i>
                        </button>
                    </div>
                    <div class="form-text">
                        <a href="https://dash.zinipay.com" target="_blank">dash.zinipay.com</a> → Brands → Copy Brand Key
                    </div>
                </div>

                <!-- Button label -->
                <div class="mb-3">
                    <label class="form-label fw-bold">পেমেন্ট বাটনের লেবেল</label>
                    <input type="text" class="form-control" name="zinipay_label"
                           value="<?= htmlspecialchars($defaults['zinipay_label']) ?>"
                           placeholder="ZiniPay (bKash/Nagad/Card)">
                    <div class="form-text">শিক্ষার্থীর পেমেন্ট পেজে বাটনে যা দেখাবে</div>
                </div>

                <!-- Callback URLs (read-only info) -->
                <div class="mb-3">
                    <label class="form-label fw-bold">Callback URLs <small class="text-muted">(ZiniPay dashboard এ সেট করুন)</small></label>
                    <div class="input-group mb-2">
                        <span class="input-group-text" style="font-size:.75rem;width:110px;">Redirect URL</span>
                        <input type="text" class="form-control form-control-sm font-monospace" readonly
                               value="<?= (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] ?>/fees/zinipay_callback.php">
                        <button class="btn btn-outline-secondary btn-sm" type="button" onclick="copyUrl(this)"><i class="fas fa-copy"></i></button>
                    </div>
                    <div class="input-group">
                        <span class="input-group-text" style="font-size:.75rem;width:110px;">Webhook URL</span>
                        <input type="text" class="form-control form-control-sm font-monospace" readonly
                               value="<?= (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] ?>/fees/zinipay_webhook.php">
                        <button class="btn btn-outline-secondary btn-sm" type="button" onclick="copyUrl(this)"><i class="fas fa-copy"></i></button>
                    </div>
                </div>
            </div>
        </div>

        <div class="d-flex gap-2 mb-4">
            <button type="submit" class="btn btn-zinipay px-4">
                <i class="fas fa-save"></i> সেটিংস সংরক্ষণ করুন
            </button>
            <button type="submit" name="test_connection" value="1" class="btn btn-outline-secondary px-4">
                <i class="fas fa-plug"></i> সংযোগ পরীক্ষা করুন
            </button>
        </div>
    </form>

    <!-- How it works -->
    <div class="card settings-card mb-4">
        <div class="card-body p-4">
            <div class="section-title">কিভাবে কাজ করে</div>
            <div class="flow-step"><div class="flow-num">১</div><div>শিক্ষার্থী <strong>my_fees.php</strong> থেকে "ZiniPay দিয়ে পেমেন্ট" বাটনে ক্লিক করে</div></div>
            <div class="flow-step"><div class="flow-num">২</div><div>ফি নির্বাচন করে ZiniPay hosted payment page এ redirect হয়</div></div>
            <div class="flow-step"><div class="flow-num">৩</div><div>bKash / Nagad / Card যেকোনো পদ্ধতিতে পেমেন্ট করে</div></div>
            <div class="flow-step"><div class="flow-num">৪</div><div>পেমেন্ট সফল হলে backend verify করে fees table আপডেট হয়</div></div>
            <div class="flow-step"><div class="flow-num">৫</div><div>শিক্ষার্থী রসিদ দেখতে পায়, admin dashboard এ payment record আসে</div></div>
        </div>
    </div>

    <!-- Info box -->
    <div class="info-box mb-4">
        <strong><i class="fas fa-info-circle text-danger"></i> গুরুত্বপূর্ণ:</strong>
        <ul class="mb-0 mt-1">
            <li>Live mode এ যাওয়ার আগে Sandbox এ ভালোভাবে টেস্ট করুন</li>
            <li>ZiniPay dashboard এ Brand এর website domain <strong><?= $_SERVER['HTTP_HOST'] ?></strong> সেট করতে হবে</li>
            <li>Webhook URL সেট করলে payment failure/retry তেও auto-update হবে</li>
        </ul>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function toggleKey() {
        const inp = document.getElementById('zinipay_api_key');
        const icon = document.getElementById('keyIcon');
        if (inp.type === 'password') {
            inp.type = 'text';
            icon.className = 'fas fa-eye-slash';
        } else {
            inp.type = 'password';
            icon.className = 'fas fa-eye';
        }
    }

    function copyUrl(btn) {
        const input = btn.previousElementSibling;
        navigator.clipboard.writeText(input.value).then(() => {
            btn.innerHTML = '<i class="fas fa-check text-success"></i>';
            setTimeout(() => btn.innerHTML = '<i class="fas fa-copy"></i>', 1500);
        });
    }
</script>
</body>
</html>
