<?php
require_once '../config/database.php';
require_once '../includes/functions.php';
$pageTitle = 'Manage Countries';
include 'side.php';

$conn = getConnection();

// ── Ensure exchange_rate column exists ────────────────────────────────────
$db = $conn->query("SELECT DATABASE() as d")->fetch_assoc()['d'];
$chk = $conn->prepare("SELECT COUNT(*) as c FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=? AND TABLE_NAME='countries' AND COLUMN_NAME='exchange_rate'");
$chk->bind_param("s",$db); $chk->execute();
if ($chk->get_result()->fetch_assoc()['c'] == 0) {
    $conn->query("ALTER TABLE countries ADD COLUMN exchange_rate DECIMAL(15,6) NOT NULL DEFAULT 1.000000 COMMENT '1 local unit = X KES. Kenya=1, Uganda≈0.026, Tanzania≈0.043'");
    $conn->query("UPDATE countries SET exchange_rate=1.000000 WHERE LOWER(currency_code)='kes' OR LOWER(name) LIKE '%kenya%'");
}

// ════════════════════════════════════════════════════════════════════════
// CURRENCY CONVENTION (single source of truth, repeated here for clarity)
//
//   exchange_rate = how many KES = 1 local unit
//   Kenya  = 1.000000  (1 KES  = 1 KES)
//   Uganda = 0.026000  (1 UGX  = 0.026 KES)
//   Tanzania = 0.043000 (1 TZS = 0.043 KES)
//
//   local → KES :  local_amount * exchange_rate
//   KES → local :  kes_amount   / exchange_rate
// ════════════════════════════════════════════════════════════════════════

// ── Handle POST actions ───────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    switch ($action) {

        case 'add':
            $name           = sanitize($_POST['name']);
            $currencyCode   = sanitize($_POST['currency_code']);
            $currencySymbol = sanitize($_POST['currency_symbol']);
            $exchangeRate   = floatval($_POST['exchange_rate']);
            $activationFee  = floatval($_POST['activation_fee']);  // stored in LOCAL currency
            $minWithdrawal  = floatval($_POST['min_withdrawal']);
            $withdrawalFee  = floatval($_POST['withdrawal_fee']);
            $activationInstructions = sanitize($_POST['activation_instructions'] ?? '');
            $contactEmail   = sanitize($_POST['contact_email'] ?? '');
            $contactPhone   = sanitize($_POST['contact_phone'] ?? '');
            $status         = sanitize($_POST['status']);

            $chk = $conn->prepare("SELECT id FROM countries WHERE name=?");
            $chk->bind_param("s",$name); $chk->execute();
            if ($chk->get_result()->num_rows > 0) {
                setFlash('error','A country with this name already exists!');
                redirect('countries.php'); exit;
            }

            $stmt = $conn->prepare("INSERT INTO countries (name,currency_code,currency_symbol,exchange_rate,activation_fee,min_withdrawal,withdrawal_fee,activation_instructions,contact_email,contact_phone,status) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
            $stmt->bind_param("sssddddssss",$name,$currencyCode,$currencySymbol,$exchangeRate,$activationFee,$minWithdrawal,$withdrawalFee,$activationInstructions,$contactEmail,$contactPhone,$status);

            if ($stmt->execute()) {
                $countryId = $conn->insert_id;
                $levelsAdded = 0;
                $lstmt = $conn->prepare("INSERT INTO commission_levels (country_id,level,commission) VALUES (?,?,?)");
                for ($lvl=1; $lvl<=5; $lvl++) {
                    $amt = floatval($_POST["level{$lvl}_commission"] ?? 0);
                    if ($amt > 0) {
                        $lstmt->bind_param("iid",$countryId,$lvl,$amt);
                        if ($lstmt->execute()) $levelsAdded++;
                    }
                }
                setFlash('success',"Country '{$name}' added! {$levelsAdded} commission levels set.");
            } else {
                setFlash('error','Failed to add country.');
            }
            break;

        case 'edit':
            $countryId = intval($_POST['country_id']);
            if ($countryId <= 0) { setFlash('error','Invalid country ID.'); redirect('countries.php'); exit; }

            $name           = sanitize($_POST['name']);
            $currencyCode   = sanitize($_POST['currency_code']);
            $currencySymbol = sanitize($_POST['currency_symbol']);
            $exchangeRate   = floatval($_POST['exchange_rate']);
            $activationFee  = floatval($_POST['activation_fee']);
            $minWithdrawal  = floatval($_POST['min_withdrawal']);
            $withdrawalFee  = floatval($_POST['withdrawal_fee']);
            $activationInstructions = sanitize($_POST['activation_instructions'] ?? '');
            $contactEmail   = sanitize($_POST['contact_email'] ?? '');
            $contactPhone   = sanitize($_POST['contact_phone'] ?? '');
            $status         = sanitize($_POST['status']);

            // Check name collision
            $cur = $conn->prepare("SELECT name FROM countries WHERE id=?");
            $cur->bind_param("i",$countryId); $cur->execute();
            $curRow = $cur->get_result()->fetch_assoc();
            if (!$curRow) { setFlash('error','Country not found!'); redirect('countries.php'); exit; }

            if ($name !== $curRow['name']) {
                $dup = $conn->prepare("SELECT id FROM countries WHERE name=?");
                $dup->bind_param("s",$name); $dup->execute();
                if ($dup->get_result()->num_rows > 0) {
                    setFlash('error',"Cannot rename — '{$name}' already exists!"); redirect('countries.php'); exit;
                }
            }

            $stmt = $conn->prepare("UPDATE countries SET name=?,currency_code=?,currency_symbol=?,exchange_rate=?,activation_fee=?,min_withdrawal=?,withdrawal_fee=?,activation_instructions=?,contact_email=?,contact_phone=?,status=? WHERE id=?");
            $stmt->bind_param("sssddddssssi",$name,$currencyCode,$currencySymbol,$exchangeRate,$activationFee,$minWithdrawal,$withdrawalFee,$activationInstructions,$contactEmail,$contactPhone,$status,$countryId);

            if ($stmt->execute()) {
                $conn->query("DELETE FROM commission_levels WHERE country_id=$countryId");
                $levelsUpdated = 0;
                $lstmt = $conn->prepare("INSERT INTO commission_levels (country_id,level,commission) VALUES (?,?,?)");
                for ($lvl=1; $lvl<=5; $lvl++) {
                    $amt = floatval($_POST["level{$lvl}_commission"] ?? 0);
                    if ($amt > 0) {
                        $lstmt->bind_param("iid",$countryId,$lvl,$amt);
                        if ($lstmt->execute()) $levelsUpdated++;
                    }
                }
                setFlash('success',"Country '{$name}' updated! {$levelsUpdated} commission levels saved.");
            } else {
                setFlash('error','Failed to update country.');
            }
            break;

        case 'save_tiers':
            $countryId = intval($_POST['country_id']);
            $conn->query("DELETE FROM withdrawal_fee_tiers WHERE country_id=$countryId");
            $tiersAdded = 0;
            if (isset($_POST['tier_min']) && is_array($_POST['tier_min'])) {
                $ts = $conn->prepare("INSERT INTO withdrawal_fee_tiers (country_id,min_amount,max_amount,fee) VALUES (?,?,?,?)");
                foreach ($_POST['tier_min'] as $i => $minA) {
                    $mn = floatval($minA); $mx = floatval($_POST['tier_max'][$i]); $fe = floatval($_POST['tier_fee'][$i]);
                    if ($mn >= 0 && $mx > $mn && $fe >= 0) { $ts->bind_param("iddd",$countryId,$mn,$mx,$fe); if ($ts->execute()) $tiersAdded++; }
                }
            }
            setFlash('success',"Withdrawal tiers updated! {$tiersAdded} tiers saved.");
            break;

        case 'delete':
            $countryId = intval($_POST['country_id']);
            $r = $conn->query("SELECT COUNT(*) as c FROM users WHERE country=(SELECT name FROM countries WHERE id=$countryId)");
            $cnt = $r->fetch_assoc()['c'];
            if ($cnt > 0) {
                setFlash('error',"Cannot delete — {$cnt} users registered.");
            } else {
                $nr = $conn->query("SELECT name FROM countries WHERE id=$countryId");
                $cname = $nr->fetch_assoc()['name'] ?? 'Unknown';
                $conn->query("DELETE FROM commission_levels WHERE country_id=$countryId");
                $conn->query("DELETE FROM withdrawal_fee_tiers WHERE country_id=$countryId");
                $conn->query("DELETE FROM countries WHERE id=$countryId");
                setFlash('success',"Country '{$cname}' deleted.");
            }
            break;

        case 'toggle_status':
            $countryId = intval($_POST['country_id']);
            $status    = sanitize($_POST['status']);
            $conn->query("UPDATE countries SET status='$status' WHERE id=$countryId");
            setFlash('success','Status updated!');
            break;
    }

    redirect('countries.php');
}

// ── Fetch all countries with commission info ───────────────────────────────
$countries = $conn->query("
    SELECT c.*,
        GROUP_CONCAT(DISTINCT CONCAT('L',cl.level,':',cl.commission) ORDER BY cl.level SEPARATOR '|') as commissions
    FROM countries c
    LEFT JOIN commission_levels cl ON c.id=cl.country_id
    GROUP BY c.id
    ORDER BY c.name ASC
");
?>
<style>
.countries-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:28px;flex-wrap:wrap;gap:12px}
.btn-add{padding:12px 24px;background:linear-gradient(135deg,#10b981,#059669);color:white;border:none;border-radius:10px;font-size:14px;font-weight:600;cursor:pointer;transition:all .3s;display:inline-flex;align-items:center;gap:8px}
.btn-add:hover{transform:translateY(-2px);box-shadow:0 8px 24px rgba(16,185,129,.4)}

.countries-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(400px,1fr));gap:20px}

.country-card{background:var(--card-bg);border:2px solid var(--border-color);border-radius:16px;padding:22px;transition:all .3s;position:relative}
.country-card:hover{border-color:var(--theme-color);transform:translateY(-3px);box-shadow:0 12px 28px rgba(0,0,0,.1)}

.country-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:14px;padding-bottom:14px;border-bottom:2px solid var(--border-color)}
.country-name{font-size:19px;font-weight:900;color:var(--text-primary);display:flex;align-items:center;gap:8px}
.country-flag{font-size:26px}
.status-badge{padding:5px 11px;border-radius:8px;font-size:11px;font-weight:700;text-transform:uppercase}
.status-active{background:rgba(16,185,129,.15);color:#10b981}
.status-inactive{background:rgba(239,68,68,.15);color:#ef4444}

.info-row{display:flex;justify-content:space-between;align-items:center;padding:9px 0;border-bottom:1px solid var(--border-color)}
.info-row:last-child{border-bottom:none}
.info-label{font-size:12px;color:var(--text-secondary);font-weight:600}
.info-value{font-size:13px;color:var(--text-primary);font-weight:700;text-align:right}
.info-value.kes{color:#10b981;font-size:11px;font-weight:600;margin-top:2px}
.dual-value{display:flex;flex-direction:column;align-items:flex-end;gap:2px}

.currency-badge{padding:3px 9px;background:var(--darker-bg);border:1px solid var(--border-color);border-radius:5px;font-family:monospace;font-size:12px;font-weight:700}

/* Commission section */
.commission-section{margin-top:14px;padding-top:14px;border-top:2px solid var(--border-color)}
.commission-title{font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-secondary);margin-bottom:8px;letter-spacing:.5px}
.commission-levels{display:flex;gap:6px;flex-wrap:wrap}
.commission-badge{padding:5px 10px;background:linear-gradient(135deg,var(--theme-color),#ec4899);color:white;border-radius:7px;font-size:11px;font-weight:700;display:flex;flex-direction:column;align-items:center;gap:1px}
.commission-badge .comm-local{font-size:11px}
.commission-badge .comm-kes{font-size:9px;opacity:.85}
.no-commissions{padding:7px 11px;background:rgba(239,68,68,.08);border:1px solid rgba(239,68,68,.25);border-radius:7px;font-size:12px;color:#ef4444;font-weight:600}

.country-actions{display:flex;gap:8px;margin-top:14px}
.btn-action{flex:1;padding:9px;border:none;border-radius:8px;font-size:12px;font-weight:600;cursor:pointer;transition:all .3s;display:flex;align-items:center;justify-content:center;gap:5px}
.btn-edit{background:var(--theme-color);color:white}
.btn-tiers{background:#f59e0b;color:white}
.btn-delete{background:#ef4444;color:white}
.btn-action:hover{transform:translateY(-2px);box-shadow:0 4px 12px rgba(0,0,0,.2)}

/* Modal */
.modal{display:none;position:fixed;inset:0;background:rgba(0,0,0,.7);z-index:10000;align-items:center;justify-content:center;padding:16px;overflow-y:auto}
.modal.active{display:flex}
.modal-content{background:var(--card-bg);border-radius:18px;padding:28px;max-width:680px;width:100%;max-height:90vh;overflow-y:auto}
.modal-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;padding-bottom:14px;border-bottom:2px solid var(--border-color)}
.modal-title{font-size:20px;font-weight:900;color:var(--text-primary)}
.modal-close{width:32px;height:32px;background:var(--darker-bg);border:none;border-radius:8px;color:var(--text-secondary);cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all .2s}
.modal-close:hover{background:var(--border-color);color:var(--text-primary)}

.form-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:16px}
.form-group{margin-bottom:0}
.form-group.full-width{grid-column:1/-1}
.form-label{display:block;font-size:13px;font-weight:600;color:var(--text-primary);margin-bottom:6px}
.form-control{width:100%;padding:10px 14px;font-size:13px;border:2px solid var(--border-color);border-radius:9px;background:var(--dark-bg);color:var(--text-primary);transition:all .3s;box-sizing:border-box}
.form-control:focus{outline:none;border-color:var(--theme-color);box-shadow:0 0 0 3px rgba(var(--theme-rgb),.1)}
textarea.form-control{resize:vertical;font-family:inherit;line-height:1.6;min-height:100px}
.form-hint{font-size:11px;color:var(--text-secondary);margin-top:4px}
.form-hint.warn{color:#f59e0b}
.form-hint.ok{color:#10b981}

/* Commission grid with KES preview */
.commission-grid{display:grid;grid-template-columns:repeat(5,1fr);gap:10px;margin-top:10px}
.commission-input-group{text-align:center}
.commission-label{font-size:10px;font-weight:700;text-transform:uppercase;color:var(--text-secondary);margin-bottom:5px}
.commission-input{text-align:center;font-weight:700}
.kes-preview{font-size:10px;color:#10b981;margin-top:3px;font-weight:600;min-height:14px}

/* Live KES calculator box */
.kes-calc-box{background:rgba(16,185,129,.06);border:1px solid rgba(16,185,129,.2);border-radius:10px;padding:12px 14px;margin-top:12px;display:none}
.kes-calc-box.visible{display:block}
.kes-calc-title{font-size:11px;font-weight:700;color:#10b981;text-transform:uppercase;letter-spacing:.5px;margin-bottom:8px}
.kes-calc-row{display:flex;justify-content:space-between;font-size:12px;padding:3px 0;border-bottom:1px solid rgba(16,185,129,.1)}
.kes-calc-row:last-child{border-bottom:none;font-weight:700;padding-top:6px}

/* Info / warning boxes */
.info-box{background:rgba(59,130,246,.08);border:1px solid rgba(59,130,246,.3);border-radius:10px;padding:13px;margin-bottom:18px;font-size:12px;color:var(--text-secondary)}
.info-box strong{color:#3b82f6}
.warning-box{background:rgba(245,158,11,.08);border:1px solid rgba(245,158,11,.3);border-radius:10px;padding:13px;margin-bottom:14px;font-size:12px;color:var(--text-secondary)}
.warning-box strong{color:#f59e0b}

.btn-primary{width:100%;padding:13px 28px;background:linear-gradient(135deg,var(--theme-color),#ec4899);color:white;border:none;border-radius:9px;font-size:14px;font-weight:600;cursor:pointer;transition:all .3s;display:inline-flex;align-items:center;justify-content:center;gap:8px;margin-top:18px}
.btn-primary:hover{transform:translateY(-2px);box-shadow:0 8px 20px rgba(var(--theme-rgb),.4)}
.btn-secondary{padding:9px 18px;background:#10b981;color:white;border:none;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;transition:all .3s;display:inline-flex;align-items:center;gap:6px}
.btn-secondary:hover{background:#059669;transform:translateY(-2px)}

/* Tiers */
.tier-row{display:grid;grid-template-columns:1fr 1fr 1fr auto;gap:10px;align-items:end;margin-bottom:10px;padding:10px;background:var(--darker-bg);border-radius:9px}
.btn-remove-tier{padding:10px 12px;background:#ef4444;color:white;border:none;border-radius:7px;cursor:pointer;transition:all .2s}
.btn-remove-tier:hover{background:#dc2626}

/* Responsive */
@media(max-width:900px){.countries-grid{grid-template-columns:repeat(2,1fr)}}
@media(max-width:640px){
    .countries-grid{grid-template-columns:1fr}
    .form-grid{grid-template-columns:1fr!important}
    .commission-grid{grid-template-columns:repeat(3,1fr)}
    .country-actions{flex-direction:column}
    .tier-row{grid-template-columns:1fr;gap:8px}
    .modal-content{padding:20px 16px;max-width:100%;margin:5px}
    .commission-grid{grid-template-columns:repeat(2,1fr)!important}
}
@media(max-width:480px){
    .countries-header{flex-direction:column;align-items:flex-start}
    .btn-add{width:100%;justify-content:center}
    .modal-content{padding:16px 12px}
}
</style>

<div class="page-header">
    <h1 class="page-title">🌍 Manage Countries</h1>
    <p class="page-subtitle">Configure countries, currencies, activation fees &amp; commission levels — all amounts shown in both local currency and KES</p>
</div>

<div class="countries-header">
    <div>
        <h2 style="font-size:19px;font-weight:700;color:var(--text-primary)">
            All Countries (<?= $countries->num_rows ?>)
        </h2>
        <p style="font-size:11px;color:var(--text-secondary);margin-top:3px">
            <span style="color:#10b981;font-weight:700">Ksh</span> values shown are KES equivalents (local × exchange rate)
        </p>
    </div>
    <button class="btn-add" onclick="openAddModal()">
        <i class="fas fa-plus-circle"></i> Add New Country
    </button>
</div>

<div class="countries-grid">
<?php
$countryFlags = [
    'Kenya'=>'🇰🇪','Tanzania'=>'🇹🇿','Uganda'=>'🇺🇬','Rwanda'=>'🇷🇼',
    'Nigeria'=>'🇳🇬','Ghana'=>'🇬🇭','South Africa'=>'🇿🇦',
    'Ethiopia'=>'🇪🇹','Egypt'=>'🇪🇬','Morocco'=>'🇲🇦',
];
while ($country = $countries->fetch_assoc()):
    $rate = max(0.000001, floatval($country['exchange_rate']));
    $sym  = htmlspecialchars($country['currency_symbol']);
    $flag = $countryFlags[$country['name']] ?? '🌍';

    // Parse commission levels
    $commissions = [];
    if ($country['commissions']) {
        foreach (explode('|', $country['commissions']) as $part) {
            [$lvl, $amt] = explode(':', $part);
            $commissions[$lvl] = floatval($amt);
        }
    }

    // KES equivalents
    $feeKes     = $country['activation_fee'] * $rate;
    $minWdKes   = $country['min_withdrawal'] * $rate;

    // Withdrawal tiers
    $tiersResult = $conn->query("SELECT * FROM withdrawal_fee_tiers WHERE country_id={$country['id']} ORDER BY min_amount ASC");
    $tiers = $tiersResult ? $tiersResult->fetch_all(MYSQLI_ASSOC) : [];
?>
    <div class="country-card">
        <div class="country-header">
            <div class="country-name">
                <span class="country-flag"><?= $flag ?></span>
                <?= htmlspecialchars($country['name']) ?>
            </div>
            <span class="status-badge status-<?= $country['status'] ?>"><?= $country['status'] ?></span>
        </div>

        <div class="country-info">
            <div class="info-row">
                <span class="info-label">Currency</span>
                <span class="currency-badge"><?= $sym ?> <?= htmlspecialchars($country['currency_code']) ?></span>
            </div>
            <div class="info-row">
                <span class="info-label">Exchange Rate</span>
                <div class="dual-value">
                    <span class="info-value">1 <?= $sym ?> = Ksh <?= number_format($rate, 4) ?></span>
                    <?php if ($rate < 1): ?>
                    <span class="kes" style="font-size:10px;color:var(--text-secondary)">
                        1 Ksh = <?= number_format(1/$rate, 2) ?> <?= htmlspecialchars($country['currency_code']) ?>
                    </span>
                    <?php endif; ?>
                </div>
            </div>
            <div class="info-row">
                <span class="info-label">Activation Fee</span>
                <div class="dual-value">
                    <span class="info-value"><?= $sym ?> <?= number_format($country['activation_fee'], 2) ?></span>
                    <?php if ($country['currency_code'] !== 'KES'): ?>
                    <span class="kes info-value">≈ Ksh <?= number_format($feeKes, 2) ?></span>
                    <?php endif; ?>
                </div>
            </div>
            <div class="info-row">
                <span class="info-label">Min Withdrawal</span>
                <div class="dual-value">
                    <span class="info-value"><?= $sym ?> <?= number_format($country['min_withdrawal'], 2) ?></span>
                    <?php if ($country['currency_code'] !== 'KES'): ?>
                    <span class="kes info-value">≈ Ksh <?= number_format($minWdKes, 2) ?></span>
                    <?php endif; ?>
                </div>
            </div>
            <div class="info-row">
                <span class="info-label">Withdrawal Fee</span>
                <?php if (!empty($tiers)): ?>
                    <span class="info-value"><?= count($tiers) ?> tiers set</span>
                <?php else: ?>
                    <div class="dual-value">
                        <span class="info-value"><?= $sym ?> <?= number_format($country['withdrawal_fee'], 2) ?></span>
                        <?php if ($country['currency_code'] !== 'KES' && $country['withdrawal_fee'] > 0): ?>
                        <span class="kes info-value">≈ Ksh <?= number_format($country['withdrawal_fee'] * $rate, 2) ?></span>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
            <?php if (!empty($country['contact_email'])): ?>
            <div class="info-row">
                <span class="info-label">Support Email</span>
                <span class="info-value" style="font-size:11px;word-break:break-all"><?= htmlspecialchars($country['contact_email']) ?></span>
            </div>
            <?php endif; ?>
        </div>

        <!-- Commission Levels: show local + KES equivalent -->
        <div class="commission-section">
            <div class="commission-title">Commission Levels (Local / KES)</div>
            <?php if (!empty($commissions)): ?>
            <div class="commission-levels">
                <?php foreach ($commissions as $lvl => $amt): $kesAmt = $amt * $rate; ?>
                <div class="commission-badge">
                    <span style="font-size:9px;opacity:.7"><?= $lvl ?></span>
                    <span class="comm-local"><?= $sym ?> <?= number_format($amt, 0) ?></span>
                    <?php if ($country['currency_code'] !== 'KES'): ?>
                    <span class="comm-kes">≈ Ksh <?= number_format($kesAmt, 0) ?></span>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
            </div>
            <?php else: ?>
            <div class="no-commissions">⚠️ No commission levels configured</div>
            <?php endif; ?>
        </div>

        <div class="country-actions">
            <button class="btn-action btn-edit" onclick="openEditModal(<?= htmlspecialchars(json_encode($country)) ?>)">
                <i class="fas fa-edit"></i> Edit
            </button>
            <button class="btn-action btn-tiers" onclick="openTiersModal(<?= $country['id'] ?>, '<?= htmlspecialchars($country['name']) ?>', '<?= $sym ?>', <?= $rate ?>)">
                <i class="fas fa-layer-group"></i> Tiers
            </button>
            <button class="btn-action btn-delete" onclick="deleteCountry(<?= $country['id'] ?>, '<?= htmlspecialchars($country['name']) ?>')">
                <i class="fas fa-trash"></i> Delete
            </button>
        </div>
    </div>
<?php endwhile; ?>
</div>

<!-- ══ ADD COUNTRY MODAL ══════════════════════════════════════════════════ -->
<div class="modal" id="addModal">
<div class="modal-content">
    <div class="modal-header">
        <h2 class="modal-title">🌍 Add New Country</h2>
        <button class="modal-close" onclick="closeModal('addModal')"><i class="fas fa-times"></i></button>
    </div>

    <div class="info-box">
        <strong><i class="fas fa-info-circle"></i> Currency Convention</strong><br>
        <strong>Exchange Rate</strong> = how many KES does 1 local unit equal.<br>
        Kenya: <strong>1.0</strong> &nbsp;·&nbsp; Uganda: <strong>~0.026</strong> &nbsp;·&nbsp; Tanzania: <strong>~0.043</strong><br>
        All fees and commissions entered in <strong>local currency</strong> — the system converts to KES automatically.
    </div>

    <form method="POST">
    <input type="hidden" name="action" value="add">
    <div class="form-grid">
        <div class="form-group">
            <label class="form-label">Country Name</label>
            <input type="text" name="name" class="form-control" required>
        </div>
        <div class="form-group">
            <label class="form-label">Status</label>
            <select name="status" class="form-control">
                <option value="active">Active</option>
                <option value="inactive">Inactive</option>
            </select>
        </div>
        <div class="form-group">
            <label class="form-label">Currency Code</label>
            <input type="text" name="currency_code" id="addCurrencyCode" class="form-control" placeholder="KES" maxlength="10" required oninput="updateAddCalc()">
            <p class="form-hint">e.g. KES, TZS, UGX, NGN</p>
        </div>
        <div class="form-group">
            <label class="form-label">Currency Symbol</label>
            <input type="text" name="currency_symbol" id="addCurrencySymbol" class="form-control" placeholder="Ksh" maxlength="10" required oninput="updateAddCalc()">
            <p class="form-hint">e.g. Ksh, TSh, USh, ₦</p>
        </div>
        <div class="form-group">
            <label class="form-label">Exchange Rate (1 local = ? KES)</label>
            <input type="number" name="exchange_rate" id="addExchangeRate" class="form-control" step="0.000001" value="1.000000" required oninput="updateAddCalc()">
            <p class="form-hint ok" id="addRateHint">Kenya / KES: enter 1.0</p>
        </div>
        <div class="form-group">
            <label class="form-label">Activation Fee (in local currency)</label>
            <input type="number" name="activation_fee" id="addActivationFee" class="form-control" step="0.01" required oninput="updateAddCalc()">
            <p class="form-hint" id="addFeeHint" style="color:#10b981"></p>
        </div>
        <div class="form-group">
            <label class="form-label">Min Withdrawal (local)</label>
            <input type="number" name="min_withdrawal" class="form-control" step="0.01" required>
        </div>
        <div class="form-group">
            <label class="form-label">Flat Withdrawal Fee (local)</label>
            <input type="number" name="withdrawal_fee" class="form-control" step="0.01" value="0.00">
            <p class="form-hint">Or use tiered fees later</p>
        </div>
    </div>

    <div class="form-group full-width" style="margin-top:16px">
        <label class="form-label">Activation Instructions (non-Kenya countries)</label>
        <textarea name="activation_instructions" class="form-control" rows="5" placeholder="Example:&#10;Send TSh 3,500 via M-Pesa to: +255 XXX XXX XXX&#10;Include your USERNAME as the reference.&#10;Activated within 24 hours."></textarea>
    </div>

    <div class="form-grid" style="margin-top:16px">
        <div class="form-group">
            <label class="form-label">Support Email</label>
            <input type="email" name="contact_email" class="form-control" placeholder="support@yoursite.com">
        </div>
        <div class="form-group">
            <label class="form-label">Support Phone / WhatsApp</label>
            <input type="text" name="contact_phone" class="form-control" placeholder="+255 XXX XXX XXX">
        </div>
    </div>

    <!-- Commission Levels -->
    <div class="form-group full-width" style="margin-top:16px">
        <label class="form-label">Commission Levels — enter in <strong>local currency</strong></label>
        <p class="form-hint warn" style="margin-bottom:8px">
            ⚠️ Fixed amounts, NOT percentages. e.g. for Kenya Ksh 200 fee: Level 1 = 20, Level 2 = 10, Level 3 = 4
        </p>
        <div class="commission-grid" id="addCommGrid">
            <?php for ($i=1;$i<=5;$i++): ?>
            <div class="commission-input-group">
                <div class="commission-label">Level <?= $i ?></div>
                <input type="number" name="level<?= $i ?>_commission" class="form-control commission-input" step="0.01" value="0.00" oninput="updateAddCalc()">
                <div class="kes-preview" id="addKes<?= $i ?>"></div>
            </div>
            <?php endfor; ?>
        </div>

        <!-- Live KES calculator -->
        <div class="kes-calc-box" id="addKesCalc">
            <div class="kes-calc-title"><i class="fas fa-calculator"></i> KES Equivalent Preview</div>
            <div id="addKesCalcRows"></div>
        </div>
    </div>

    <button type="submit" class="btn-primary"><i class="fas fa-plus-circle"></i> Add Country</button>
    </form>
</div>
</div>

<!-- ══ EDIT COUNTRY MODAL ════════════════════════════════════════════════ -->
<div class="modal" id="editModal">
<div class="modal-content">
    <div class="modal-header">
        <h2 class="modal-title">✏️ Edit Country</h2>
        <button class="modal-close" onclick="closeModal('editModal')"><i class="fas fa-times"></i></button>
    </div>

    <form method="POST" id="editForm">
    <input type="hidden" name="action" value="edit">
    <input type="hidden" name="country_id" id="editCountryId">
    <div class="form-grid">
        <div class="form-group">
            <label class="form-label">Country Name</label>
            <input type="text" name="name" id="editName" class="form-control" required>
        </div>
        <div class="form-group">
            <label class="form-label">Status</label>
            <select name="status" id="editStatus" class="form-control">
                <option value="active">Active</option>
                <option value="inactive">Inactive</option>
            </select>
        </div>
        <div class="form-group">
            <label class="form-label">Currency Code</label>
            <input type="text" name="currency_code" id="editCurrencyCode" class="form-control" required oninput="updateEditCalc()">
        </div>
        <div class="form-group">
            <label class="form-label">Currency Symbol</label>
            <input type="text" name="currency_symbol" id="editCurrencySymbol" class="form-control" required oninput="updateEditCalc()">
        </div>
        <div class="form-group">
            <label class="form-label">Exchange Rate (1 local = ? KES)</label>
            <input type="number" name="exchange_rate" id="editExchangeRate" class="form-control" step="0.000001" required oninput="updateEditCalc()">
            <p class="form-hint ok">Kenya=1.0 &nbsp;·&nbsp; Uganda≈0.026 &nbsp;·&nbsp; Tanzania≈0.043</p>
        </div>
        <div class="form-group">
            <label class="form-label">Activation Fee (local)</label>
            <input type="number" name="activation_fee" id="editActivationFee" class="form-control" step="0.01" required oninput="updateEditCalc()">
            <p class="form-hint" id="editFeeHint" style="color:#10b981"></p>
        </div>
        <div class="form-group">
            <label class="form-label">Min Withdrawal (local)</label>
            <input type="number" name="min_withdrawal" id="editMinWithdrawal" class="form-control" step="0.01" required>
        </div>
        <div class="form-group">
            <label class="form-label">Flat Withdrawal Fee (local)</label>
            <input type="number" name="withdrawal_fee" id="editWithdrawalFee" class="form-control" step="0.01">
        </div>
    </div>

    <div class="form-group full-width" style="margin-top:16px">
        <label class="form-label">Activation Instructions</label>
        <textarea name="activation_instructions" id="editActivationInstructions" class="form-control" rows="5"></textarea>
    </div>

    <div class="form-grid" style="margin-top:16px">
        <div class="form-group">
            <label class="form-label">Support Email</label>
            <input type="email" name="contact_email" id="editContactEmail" class="form-control">
        </div>
        <div class="form-group">
            <label class="form-label">Support Phone / WhatsApp</label>
            <input type="text" name="contact_phone" id="editContactPhone" class="form-control">
        </div>
    </div>

    <!-- Commission Levels with live KES preview -->
    <div class="form-group full-width" style="margin-top:16px">
        <label class="form-label">Commission Levels (local currency)</label>
        <p class="form-hint warn" style="margin-bottom:8px">⚠️ Fixed amounts in local currency — KES equivalents shown below each field live</p>
        <div class="commission-grid">
            <?php for ($i=1;$i<=5;$i++): ?>
            <div class="commission-input-group">
                <div class="commission-label">Level <?= $i ?></div>
                <input type="number" name="level<?= $i ?>_commission" id="editLevel<?= $i ?>" class="form-control commission-input" step="0.01" value="0.00" oninput="updateEditCalc()">
                <div class="kes-preview" id="editKes<?= $i ?>"></div>
            </div>
            <?php endfor; ?>
        </div>

        <div class="kes-calc-box" id="editKesCalc">
            <div class="kes-calc-title"><i class="fas fa-calculator"></i> KES Equivalent Preview</div>
            <div id="editKesCalcRows"></div>
        </div>
    </div>

    <button type="submit" class="btn-primary"><i class="fas fa-save"></i> Save Changes</button>
    </form>
</div>
</div>

<!-- ══ WITHDRAWAL TIERS MODAL ════════════════════════════════════════════ -->
<div class="modal" id="tiersModal">
<div class="modal-content">
    <div class="modal-header">
        <h2 class="modal-title">💰 Withdrawal Tiers — <span id="tiersCountryName"></span></h2>
        <button class="modal-close" onclick="closeModal('tiersModal')"><i class="fas fa-times"></i></button>
    </div>

    <div class="warning-box">
        <strong><i class="fas fa-info-circle"></i> Fee amounts in local currency</strong><br>
        Enter all amounts in <strong id="tiersCurrencyLabel">local currency</strong>.
        KES equivalents: <strong id="tiersKesNote"></strong>
    </div>

    <form method="POST" id="tiersForm">
    <input type="hidden" name="action" value="save_tiers">
    <input type="hidden" name="country_id" id="tiersCountryId">
    <div id="tiersContainer"></div>
    <button type="button" class="btn-secondary" onclick="addTierRow()" style="margin-top:14px">
        <i class="fas fa-plus"></i> Add Tier
    </button>
    <button type="submit" class="btn-primary"><i class="fas fa-save"></i> Save Tiers</button>
    </form>
</div>
</div>

<script>
// ── Global state ─────────────────────────────────────────────────────────
let currentCurrencySymbol = 'Ksh';
let currentExchangeRate   = 1.0;
let tierCounter = 0;

// ── Modal helpers ─────────────────────────────────────────────────────────
function closeModal(id) { document.getElementById(id).classList.remove('active'); }
document.querySelectorAll('.modal').forEach(m => m.addEventListener('click', e => { if (e.target === m) m.classList.remove('active'); }));

function openAddModal() { document.getElementById('addModal').classList.add('active'); updateAddCalc(); }
function closeAddModal() { closeModal('addModal'); }
function closeEditModal() { closeModal('editModal'); }

// ── Live KES calculator for ADD modal ────────────────────────────────────
function updateAddCalc() {
    const rate = parseFloat(document.getElementById('addExchangeRate').value) || 1;
    const sym  = document.getElementById('addCurrencySymbol').value || '?';
    const code = document.getElementById('addCurrencyCode').value || '';
    const fee  = parseFloat(document.getElementById('addActivationFee').value) || 0;

    // Update rate hint
    const hint = document.getElementById('addRateHint');
    if (rate > 0 && rate !== 1) {
        hint.textContent = `1 ${sym} = Ksh ${rate.toFixed(6)} · 1 Ksh = ${(1/rate).toFixed(2)} ${code}`;
        hint.className = 'form-hint ok';
    }

    // Activation fee KES hint
    if (fee > 0) {
        document.getElementById('addFeeHint').textContent = `≈ Ksh ${(fee * rate).toFixed(2)}`;
    }

    // Commission level previews
    let calcHtml = '', anyComm = false;
    for (let i = 1; i <= 5; i++) {
        const input = document.querySelector(`#addCommGrid input[name="level${i}_commission"]`);
        const amt = parseFloat(input?.value) || 0;
        const kesEl = document.getElementById('addKes' + i);
        if (amt > 0) {
            const kes = amt * rate;
            if (kesEl) kesEl.textContent = '≈ Ksh ' + kes.toFixed(2);
            calcHtml += `<div class="kes-calc-row"><span>Level ${i}: ${sym} ${amt.toFixed(2)}</span><span>Ksh ${kes.toFixed(2)}</span></div>`;
            anyComm = true;
        } else {
            if (kesEl) kesEl.textContent = '';
        }
    }

    const box = document.getElementById('addKesCalc');
    if (anyComm) {
        box.classList.add('visible');
        // Total
        let totalKes = 0;
        for (let i = 1; i <= 5; i++) {
            const v = parseFloat(document.querySelector(`#addCommGrid input[name="level${i}_commission"]`)?.value) || 0;
            totalKes += v * rate;
        }
        const feeKes = fee * rate;
        calcHtml += `<div class="kes-calc-row"><span>Total commissions</span><span>Ksh ${totalKes.toFixed(2)}</span></div>`;
        if (feeKes > 0) {
            const keep = feeKes - totalKes;
            calcHtml += `<div class="kes-calc-row" style="color:${keep>=0?'#10b981':'#ef4444'}"><span>You keep (fee − commissions)</span><span>Ksh ${keep.toFixed(2)}</span></div>`;
        }
        document.getElementById('addKesCalcRows').innerHTML = calcHtml;
    } else {
        box.classList.remove('visible');
    }
}

// ── Open EDIT modal ───────────────────────────────────────────────────────
function openEditModal(country) {
    document.getElementById('editCountryId').value              = country.id;
    document.getElementById('editName').value                   = country.name;
    document.getElementById('editStatus').value                 = country.status;
    document.getElementById('editCurrencyCode').value           = country.currency_code;
    document.getElementById('editCurrencySymbol').value         = country.currency_symbol;
    document.getElementById('editExchangeRate').value           = country.exchange_rate;
    document.getElementById('editActivationFee').value          = country.activation_fee;
    document.getElementById('editMinWithdrawal').value          = country.min_withdrawal;
    document.getElementById('editWithdrawalFee').value          = country.withdrawal_fee;
    document.getElementById('editActivationInstructions').value = country.activation_instructions || '';
    document.getElementById('editContactEmail').value           = country.contact_email || '';
    document.getElementById('editContactPhone').value           = country.contact_phone || '';

    // Set commission levels
    for (let i = 1; i <= 5; i++) document.getElementById('editLevel' + i).value = '0.00';
    if (country.commissions) {
        country.commissions.split('|').forEach(part => {
            const [lvl, amt] = part.split(':');
            const n = lvl.replace('L','');
            const el = document.getElementById('editLevel' + n);
            if (el) el.value = parseFloat(amt).toFixed(2);
        });
    }

    document.getElementById('editModal').classList.add('active');
    updateEditCalc();
}

// ── Live KES calculator for EDIT modal ───────────────────────────────────
function updateEditCalc() {
    const rate = parseFloat(document.getElementById('editExchangeRate').value) || 1;
    const sym  = document.getElementById('editCurrencySymbol').value || '?';
    const fee  = parseFloat(document.getElementById('editActivationFee').value) || 0;

    if (fee > 0) {
        document.getElementById('editFeeHint').textContent = `≈ Ksh ${(fee * rate).toFixed(2)}`;
    } else {
        document.getElementById('editFeeHint').textContent = '';
    }

    let calcHtml = '', anyComm = false, totalKes = 0;
    for (let i = 1; i <= 5; i++) {
        const amt = parseFloat(document.getElementById('editLevel' + i).value) || 0;
        const kesEl = document.getElementById('editKes' + i);
        if (amt > 0) {
            const kes = amt * rate;
            totalKes += kes;
            if (kesEl) kesEl.textContent = '≈ Ksh ' + kes.toFixed(2);
            calcHtml += `<div class="kes-calc-row"><span>Level ${i}: ${sym} ${amt.toFixed(2)}</span><span>Ksh ${kes.toFixed(2)}</span></div>`;
            anyComm = true;
        } else {
            if (kesEl) kesEl.textContent = '';
        }
    }

    const box = document.getElementById('editKesCalc');
    if (anyComm) {
        box.classList.add('visible');
        calcHtml += `<div class="kes-calc-row"><span>Total commissions</span><span>Ksh ${totalKes.toFixed(2)}</span></div>`;
        const feeKes = fee * rate;
        if (feeKes > 0) {
            const keep = feeKes - totalKes;
            calcHtml += `<div class="kes-calc-row" style="color:${keep>=0?'#10b981':'#ef4444'}"><span>You keep (fee − commissions)</span><span>Ksh ${keep.toFixed(2)}</span></div>`;
        }
        document.getElementById('editKesCalcRows').innerHTML = calcHtml;
    } else {
        box.classList.remove('visible');
    }
}

// ── Withdrawal tiers modal ────────────────────────────────────────────────
function openTiersModal(countryId, countryName, sym, rate) {
    currentCurrencySymbol = sym;
    currentExchangeRate   = rate;
    document.getElementById('tiersCountryId').value = countryId;
    document.getElementById('tiersCountryName').textContent = countryName;
    document.getElementById('tiersCurrencyLabel').textContent = sym;
    document.getElementById('tiersKesNote').textContent = `1 ${sym} = Ksh ${parseFloat(rate).toFixed(4)}`;

    fetch(`get_tiers.php?country_id=${countryId}`)
        .then(r => r.json())
        .then(tiers => {
            const container = document.getElementById('tiersContainer');
            container.innerHTML = ''; tierCounter = 0;
            if (tiers.length > 0) {
                tiers.forEach(t => addTierRow(t.min_amount, t.max_amount, t.fee));
            } else {
                addTierRow(0, 500, 20);
                addTierRow(501, 2000, 50);
                addTierRow(2001, 5000, 100);
                addTierRow(5001, 999999, 150);
            }
        })
        .catch(() => {
            const container = document.getElementById('tiersContainer');
            container.innerHTML = ''; tierCounter = 0;
            addTierRow(0,500,20); addTierRow(501,2000,50);
            addTierRow(2001,5000,100); addTierRow(5001,999999,150);
        });

    document.getElementById('tiersModal').classList.add('active');
}

function closeTiersModal() { closeModal('tiersModal'); }

function addTierRow(min='', max='', fee='') {
    const rowId = 'tier-' + tierCounter++;
    const row = document.createElement('div');
    row.className = 'tier-row'; row.id = rowId;
    const rate = currentExchangeRate;
    const sym  = currentCurrencySymbol;
    row.innerHTML = `
        <div class="form-group">
            <label class="form-label">Min (${sym})</label>
            <input type="number" name="tier_min[]" class="form-control" step="0.01" value="${min}" required>
        </div>
        <div class="form-group">
            <label class="form-label">Max (${sym})</label>
            <input type="number" name="tier_max[]" class="form-control" step="0.01" value="${max}" required>
        </div>
        <div class="form-group">
            <label class="form-label">Fee (${sym}) ${rate !== 1 ? `<span style="color:#10b981;font-size:10px">≈ Ksh ${(parseFloat(fee||0)*rate).toFixed(2)}</span>` : ''}</label>
            <input type="number" name="tier_fee[]" class="form-control" step="0.01" value="${fee}" required>
        </div>
        <button type="button" class="btn-remove-tier" onclick="document.getElementById('${rowId}').remove()">
            <i class="fas fa-trash"></i>
        </button>`;
    document.getElementById('tiersContainer').appendChild(row);
}

// ── Delete ────────────────────────────────────────────────────────────────
function deleteCountry(id, name) {
    if (!confirm(`Delete "${name}"?\n\nCountries with existing users cannot be deleted.`)) return;
    const f = document.createElement('form'); f.method='POST';
    f.innerHTML = `<input type="hidden" name="action" value="delete"><input type="hidden" name="country_id" value="${id}">`;
    document.body.appendChild(f); f.submit();
}
</script>

<?php include 'footer.php'; ?>