<?php
require_once '../includes/config.php';
require_once '../includes/dingconnect.php';
requireAdmin();
$db = getDB();

$flash = $_SESSION['flash'] ?? null;
unset($_SESSION['flash']);

// Toggle country enable/disable
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'toggle_country') {
    $iso     = strtoupper(sanitize($_POST['iso'] ?? ''));
    $enabled = intval($_POST['enabled'] ?? 0);
    if ($iso) {
        try {
            $db->prepare("UPDATE intl_countries SET is_enabled=? WHERE iso=?")->execute([$enabled, $iso]);
            echo json_encode(['success'=>true]);
        } catch(Exception $e) {
            echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
        }
        exit;
    }
}

// Reorder countries
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save_order') {
    $isos = json_decode($_POST['isos'] ?? '[]', true);
    $stmt = $db->prepare("UPDATE intl_countries SET sort_order=? WHERE iso=?");
    foreach ($isos as $i => $iso) $stmt->execute([$i+1, $iso]);
    echo json_encode(['success'=>true]); exit;
}

// Save settings
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save_settings') {
    $fields = ['ding_api_key','ding_mode','ding_notify_telegram'];
    foreach ($fields as $k) {
        $v = sanitize($_POST[$k] ?? '');
        $db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")->execute([$k,$v,$v]);
    }
    $_SESSION['flash'] = ['type'=>'success','msg'=>'✅ DingConnect সেটিংস সেভ হয়েছে!'];
    header('Location: international.php'); exit;
}

// Filters
$filterStatus = sanitize($_GET['status'] ?? '');
$filterType   = sanitize($_GET['type']   ?? '');
$filterSearch = sanitize($_GET['search'] ?? '');

// All DingConnect related types
$dingTypes = "('international','pin','gift','card')";

$where  = "WHERE t.type IN $dingTypes";
$params = [];
if ($filterStatus) { $where .= " AND t.status=?"; $params[] = $filterStatus; }
if ($filterType)   { $where .= " AND t.type=?";   $params[] = $filterType; }
if ($filterSearch) {
    $where .= " AND (u.name LIKE ? OR u.username LIKE ? OR t.phone_number LIKE ? OR t.reference LIKE ?)";
    $params = array_merge($params, ["%$filterSearch%","%$filterSearch%","%$filterSearch%","%$filterSearch%"]);
}

$stmt = $db->prepare("SELECT t.*, u.name as uname, u.username FROM transactions t JOIN users u ON t.user_id=u.id $where ORDER BY t.created_at DESC LIMIT 100");
$stmt->execute($params);
$txns = $stmt->fetchAll();

// Stats — all DingConnect types
$stats = [
    'total'      => $db->query("SELECT COUNT(*) FROM transactions WHERE type IN $dingTypes")->fetchColumn(),
    'pending'    => $db->query("SELECT COUNT(*) FROM transactions WHERE type IN $dingTypes AND status='pending'")->fetchColumn(),
    'processing' => $db->query("SELECT COUNT(*) FROM transactions WHERE type IN $dingTypes AND status='processing'")->fetchColumn(),
    'success'    => $db->query("SELECT COUNT(*) FROM transactions WHERE type IN $dingTypes AND status='success'")->fetchColumn(),
    'failed'     => $db->query("SELECT COUNT(*) FROM transactions WHERE type IN $dingTypes AND status IN ('failed','refunded')")->fetchColumn(),
    'revenue'    => $db->query("SELECT COALESCE(SUM(amount),0) FROM transactions WHERE type IN $dingTypes AND status='success'")->fetchColumn(),
    'today'      => $db->query("SELECT COUNT(*) FROM transactions WHERE type IN $dingTypes AND DATE(created_at)=CURDATE()")->fetchColumn(),
    'today_rev'  => $db->query("SELECT COALESCE(SUM(amount),0) FROM transactions WHERE type IN $dingTypes AND status='success' AND DATE(created_at)=CURDATE()")->fetchColumn(),
    // Per type counts
    'intl_count' => $db->query("SELECT COUNT(*) FROM transactions WHERE type='international'")->fetchColumn(),
    'pin_count'  => $db->query("SELECT COUNT(*) FROM transactions WHERE type='pin'")->fetchColumn(),
    'gift_count' => $db->query("SELECT COUNT(*) FROM transactions WHERE type='gift'")->fetchColumn(),
    'card_count' => $db->query("SELECT COUNT(*) FROM transactions WHERE type='card'")->fetchColumn(),
];

$ding_settings = [];
foreach ($db->query("SELECT * FROM settings WHERE `key` LIKE 'ding_%'")->fetchAll() as $s) {
    $ding_settings[$s['key']] = $s['value'];
}

// Flag helper
function isoToFlagAdmin($iso) {
    if (!$iso || strlen($iso) !== 2) return '🌍';
    $offset = 127397;
    return mb_chr(ord($iso[0]) + $offset) . mb_chr(ord($iso[1]) + $offset);
}

// Countries list for management
try {
    $allCountries = $db->query("SELECT iso, name, is_enabled, sort_order FROM intl_countries ORDER BY sort_order, name")->fetchAll();
} catch(Exception $e) {
    $allCountries = [];
}

$enabledCount  = count(array_filter($allCountries, function($c) { return $c['is_enabled']; }));
$disabledCount = count($allCountries) - $enabledCount;
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>International - Admin</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../assets/css/admin.css">
    <style>
        .hero{background:linear-gradient(135deg,#0f2460,#1a3c8f);border-radius:16px;padding:22px;color:white;margin-bottom:20px;display:flex;align-items:center;gap:18px}
        .hero-icon{width:56px;height:56px;background:rgba(255,255,255,0.15);border-radius:14px;display:flex;align-items:center;justify-content:center;font-size:24px;flex-shrink:0}
        .hero h2{font-size:18px;font-weight:800;margin-bottom:3px}
        .hero p{font-size:12px;opacity:0.75}
        .hero-pills{display:flex;gap:8px;margin-top:8px;flex-wrap:wrap}
        .hero-pill{background:rgba(255,255,255,0.18);padding:3px 11px;border-radius:20px;font-size:11px;font-weight:600}
        .stats-row{display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin-bottom:20px}
        .stat-box{background:white;border-radius:14px;padding:16px;box-shadow:0 2px 10px rgba(0,0,0,0.05);text-align:center}
        .stat-box h3{font-size:22px;font-weight:800;margin-bottom:4px}
        .stat-box p{font-size:11px;color:#888}
        .stat-box.blue h3{color:var(--primary)}
        .stat-box.yellow h3{color:#d69e2e}
        .stat-box.green h3{color:#38a169}
        .stat-box.red h3{color:#e53e3e}
        .settings-card{background:white;border-radius:16px;padding:22px;box-shadow:0 2px 12px rgba(0,0,0,0.05);margin-bottom:20px}
        .settings-title{font-size:15px;font-weight:700;color:var(--dark);margin-bottom:16px;display:flex;align-items:center;gap:8px}
        .form-group{margin-bottom:14px}
        .form-group label{display:block;font-size:13px;color:#555;margin-bottom:5px;font-weight:600}
        .form-group input{width:100%;padding:11px 13px;border:2px solid #e8ecf4;border-radius:10px;font-size:14px;outline:none;transition:0.2s}
        .form-group input:focus{border-color:var(--primary)}
        .mode-toggle{display:grid;grid-template-columns:1fr 1fr;gap:10px}
        .mode-opt{border:2px solid #e8ecf4;border-radius:12px;padding:14px;cursor:pointer;transition:0.2s;position:relative}
        .mode-opt:has(input:checked){border-color:var(--primary);background:#f0f4ff}
        .mode-opt input{position:absolute;opacity:0;width:0;height:0}
        .mode-opt h4{font-size:14px;font-weight:700;margin-bottom:3px}
        .mode-opt p{font-size:12px;color:#888}
        .info-box{background:#f0f4ff;border-radius:10px;padding:12px 14px;font-size:13px;color:#444;margin-bottom:14px}
        .info-box a{color:var(--primary);font-weight:600}
        .btn-group{display:flex;gap:10px;flex-wrap:wrap}
        .btn-save{background:linear-gradient(135deg,var(--primary),#2856c8);color:white;border:none;padding:11px 22px;border-radius:10px;font-size:14px;font-weight:700;cursor:pointer}
        .btn-test{background:#f0f4ff;color:var(--primary);border:2px solid #e8ecf4;padding:11px 18px;border-radius:10px;font-size:14px;font-weight:600;cursor:pointer}
        .test-result{font-size:13px;padding:10px 14px;border-radius:8px;margin-top:10px;display:none}
        .test-ok{background:#f0fff4;color:#276749;border-left:4px solid #38a169}
        .test-fail{background:#fff5f5;color:#c53030;border-left:4px solid #e53e3e}

        /* Transaction Table */
        .txn-table-wrap{background:white;border-radius:16px;box-shadow:0 2px 12px rgba(0,0,0,0.05);overflow:hidden}
        .txn-header{padding:16px 20px;border-bottom:2px solid #f5f5f5;display:flex;align-items:center;justify-content:space-between}
        .txn-header h3{font-size:15px;font-weight:700;color:var(--dark)}
        .txn-count{font-size:13px;color:#888}
        table{width:100%;border-collapse:collapse;font-size:13px}
        th{background:#f8fafc;padding:11px 14px;text-align:left;color:#666;font-weight:600;border-bottom:2px solid #eee;white-space:nowrap}
        td{padding:11px 14px;border-bottom:1px solid #f5f5f5;vertical-align:middle}
        tr:last-child td{border:none}
        tr:hover td{background:#fafbff}
        .badge{display:inline-block;padding:3px 10px;border-radius:20px;font-size:11px;font-weight:700}
        .badge-pending{background:#fffaf0;color:#d69e2e}
        .badge-processing{background:#ebf8ff;color:#3182ce}
        .badge-success{background:#f0fff4;color:#38a169}
        .badge-failed,.badge-refunded{background:#fff5f5;color:#e53e3e}
        .note-text{font-size:11px;color:#888;max-width:200px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
        .btn-sm{padding:5px 10px;border:none;border-radius:7px;font-size:11px;cursor:pointer;font-weight:600}
        .btn-ok{background:#f0fff4;color:#38a169}
        .btn-ok:hover{background:#38a169;color:white}
        .btn-rj{background:#fff5f5;color:#e53e3e}
        .btn-rj:hover{background:#e53e3e;color:white}
        .today-stats{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-bottom:20px}
        .today-box{background:linear-gradient(135deg,#1a3c8f,#2856c8);border-radius:14px;padding:16px;color:white}
        .today-box h3{font-size:24px;font-weight:800}
        .today-box p{font-size:12px;opacity:0.8;margin-top:4px}
        .table-responsive{overflow-x:auto}
        .toggle-sw{width:44px;height:24px;background:#ddd;border-radius:20px;position:relative;cursor:pointer;transition:0.3s;flex-shrink:0}
        .toggle-sw.on{background:#38a169}
        .toggle-knob{width:20px;height:20px;background:white;border-radius:50%;position:absolute;top:2px;left:2px;transition:0.3s;box-shadow:0 1px 4px rgba(0,0,0,0.2)}
        .toggle-sw.on .toggle-knob{left:22px}
        .country-row:last-child{border-bottom:none!important}
        @media(max-width:900px){.stats-row{grid-template-columns:1fr 1fr}.mode-toggle{grid-template-columns:1fr}.today-stats{grid-template-columns:1fr 1fr}}
    </style>
</head>
<body>
<?php include '../includes/admin_sidebar.php'; ?>

<div class="main">
    <div class="topbar">
        <div class="topbar-left">
            <button class="menu-toggle" onclick="openSidebar()"><i class="fas fa-bars"></i></button>
            <h1><i class="fas fa-globe"></i> International Recharge</h1>
        </div>
        <div class="topbar-right">
            <span style="font-size:13px">
                <span style="width:10px;height:10px;border-radius:50%;background:<?= dingIsConfigured()?'#38a169':'#e53e3e' ?>;display:inline-block;margin-right:6px"></span>
                DingConnect: <?= dingIsConfigured()?'<span style="color:#38a169;font-weight:600">Connected</span>':'<span style="color:#e53e3e">Not Set</span>' ?>
            </span>
        </div>
    </div>

    <div class="content">
        <?php if ($flash): ?>
        <div class="flash flash-<?= $flash['type'] ?>"><?= $flash['msg'] ?></div>
        <?php endif; ?>

        <!-- Hero -->
        <div class="hero">
            <div class="hero-icon"><i class="fas fa-globe"></i></div>
            <div>
                <h2>DingConnect International API</h2>
                <p>150+ দেশে, 850+ অপারেটরে মোবাইল রিচার্জ</p>
                <div class="hero-pills">
                    <span class="hero-pill">🌍 150+ Countries</span>
                    <span class="hero-pill">📱 850+ Operators</span>
                    <span class="hero-pill">⚡ Real-time</span>
                </div>
            </div>
        </div>

        <!-- Overall Stats -->
        <div class="stats-row">
            <div class="stat-box blue">
                <h3><?= $stats['total'] ?></h3>
                <p>Total Transactions</p>
            </div>
            <div class="stat-box yellow">
                <h3><?= $stats['pending'] + $stats['processing'] ?></h3>
                <p>Pending / Processing</p>
            </div>
            <div class="stat-box green">
                <h3><?= $stats['success'] ?></h3>
                <p>Successful</p>
            </div>
            <div class="stat-box green">
                <h3><?= CURRENCY ?><?= number_format($stats['revenue'],0) ?></h3>
                <p>Total Revenue</p>
            </div>
        </div>

        <!-- Type Breakdown -->
        <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:20px">
            <div style="background:white;border-radius:12px;padding:14px;box-shadow:0 2px 8px rgba(0,0,0,0.05);text-align:center;border-top:3px solid #1a3c8f">
                <div style="font-size:20px;margin-bottom:4px">🌍</div>
                <div style="font-size:20px;font-weight:800;color:#1a3c8f"><?= $stats['intl_count'] ?></div>
                <div style="font-size:11px;color:#888">Recharge</div>
            </div>
            <div style="background:white;border-radius:12px;padding:14px;box-shadow:0 2px 8px rgba(0,0,0,0.05);text-align:center;border-top:3px solid #b7791f">
                <div style="font-size:20px;margin-bottom:4px">🔑</div>
                <div style="font-size:20px;font-weight:800;color:#b7791f"><?= $stats['pin_count'] ?></div>
                <div style="font-size:11px;color:#888">PIN</div>
            </div>
            <div style="background:white;border-radius:12px;padding:14px;box-shadow:0 2px 8px rgba(0,0,0,0.05);text-align:center;border-top:3px solid #805ad5">
                <div style="font-size:20px;margin-bottom:4px">🎁</div>
                <div style="font-size:20px;font-weight:800;color:#805ad5"><?= $stats['gift_count'] ?></div>
                <div style="font-size:11px;color:#888">Gift Card</div>
            </div>
            <div style="background:white;border-radius:12px;padding:14px;box-shadow:0 2px 8px rgba(0,0,0,0.05);text-align:center;border-top:3px solid #2c7a7b">
                <div style="font-size:20px;margin-bottom:4px">📞</div>
                <div style="font-size:20px;font-weight:800;color:#2c7a7b"><?= $stats['card_count'] ?></div>
                <div style="font-size:11px;color:#888">Calling Card</div>
            </div>
        </div>

        <!-- Today Stats -->
        <div class="today-stats">
            <div class="today-box">
                <h3><?= $stats['today'] ?></h3>
                <p>📅 আজকের রিচার্জ</p>
            </div>
            <div class="today-box" style="background:linear-gradient(135deg,#276749,#38a169)">
                <h3><?= CURRENCY ?><?= number_format($stats['today_rev'],2) ?></h3>
                <p>💰 আজকের আয়</p>
            </div>
        </div>

        <!-- Settings -->
        <div class="settings-card">
            <div class="settings-title"><i class="fas fa-sync" style="color:#38a169"></i> Products DB Sync</div>
            <?php
            $lastSync = getSetting('intl_last_sync') ?: 'কখনো sync হয়নি';
            $usdRate  = getSetting('intl_usd_rate')  ?: '110';
            try { $dbCount = $db->query("SELECT COUNT(*) FROM intl_products WHERE is_active=1")->fetchColumn(); }
            catch(Exception $e) { $dbCount = 0; }
            ?>
            <div style="background:#f0fff4;border-radius:10px;padding:12px 14px;margin-bottom:14px;font-size:13px">
                📦 DB তে <strong><?= number_format($dbCount) ?></strong> products আছে •
                🕐 Last sync: <strong><?= $lastSync ?></strong> •
                💱 Rate: <strong>৳<?= $usdRate ?>/USD</strong>
            </div>

            <!-- USD Rate Update -->
            <div class="form-group">
                <label>💱 USD → BDT Rate (এটা দিয়ে সব price হিসাব হবে)</label>
                <div style="display:flex;gap:10px">
                    <input type="number" id="usdRate" value="<?= $usdRate ?>" min="50" max="500" step="0.5" style="flex:1;padding:10px 13px;border:2px solid #e8ecf4;border-radius:10px;font-size:14px;outline:none">
                    <button onclick="updateRate()" style="background:#38a169;color:white;border:none;padding:10px 18px;border-radius:10px;font-size:14px;font-weight:600;cursor:pointer;white-space:nowrap">Rate আপডেট</button>
                </div>
            </div>

            <!-- Sync Buttons -->
            <div style="font-size:13px;font-weight:600;color:#555;margin-bottom:8px">DingConnect থেকে Sync করুন:</div>
            <div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:10px">
                <button onclick="syncCountries()" style="background:#f0f4ff;color:var(--primary);border:2px solid #e8ecf4;padding:9px 15px;border-radius:10px;font-size:13px;font-weight:600;cursor:pointer">
                    🌍 দেশ Sync
                </button>
                <button onclick="syncCountry('BD')" style="background:#f0f4ff;color:var(--primary);border:2px solid #e8ecf4;padding:9px 15px;border-radius:10px;font-size:13px;font-weight:600;cursor:pointer">
                    🇧🇩 Bangladesh
                </button>
                <button onclick="syncCountry('IN')" style="background:#f0f4ff;color:var(--primary);border:2px solid #e8ecf4;padding:9px 15px;border-radius:10px;font-size:13px;font-weight:600;cursor:pointer">
                    🇮🇳 India
                </button>
                <button onclick="syncCountry('SA')" style="background:#f0f4ff;color:var(--primary);border:2px solid #e8ecf4;padding:9px 15px;border-radius:10px;font-size:13px;font-weight:600;cursor:pointer">
                    🇸🇦 Saudi Arabia
                </button>
                <button onclick="syncCountry('AE')" style="background:#f0f4ff;color:var(--primary);border:2px solid #e8ecf4;padding:9px 15px;border-radius:10px;font-size:13px;font-weight:600;cursor:pointer">
                    🇦🇪 UAE
                </button>
                <button onclick="syncCountry('MY')" style="background:#f0f4ff;color:var(--primary);border:2px solid #e8ecf4;padding:9px 15px;border-radius:10px;font-size:13px;font-width:600;cursor:pointer">
                    🇲🇾 Malaysia
                </button>
                <button onclick="syncAllRegex(this)" style="background:#276749;color:white;border:none;padding:9px 15px;border-radius:10px;font-size:13px;font-weight:600;cursor:pointer">
                    🔄 Sync All Phone Regex
                </button>
            </div>
            <!-- Custom Country Sync -->
            <div style="display:flex;gap:8px">
                <input type="text" id="customCountry" placeholder="ISO code (যেমন: KW, QA, PK)" maxlength="2" style="flex:1;padding:9px 13px;border:2px solid #e8ecf4;border-radius:10px;font-size:13px;outline:none;text-transform:uppercase">
                <button onclick="syncCustom()" style="background:var(--primary);color:white;border:none;padding:9px 16px;border-radius:10px;font-size:13px;font-weight:600;cursor:pointer">Sync</button>
            </div>
            <div id="syncResult" style="margin-top:10px;padding:10px 14px;border-radius:8px;font-size:13px;display:none"></div>
        </div>

        <!-- Country Management -->
        <div class="settings-card">
            <div class="settings-title" style="display:flex;align-items:center">
                <i class="fas fa-flag" style="color:#38a169;margin-right:8px"></i> Country Management
                <span style="margin-left:auto;font-size:12px;color:#888;font-weight:400">
                    ✅ <?= $enabledCount ?> enabled &nbsp;|&nbsp; <?= $disabledCount ?> disabled
                </span>
            </div>
            <p style="font-size:13px;color:#666;margin-bottom:14px">Enable countries to show in user app (International & Cards page).</p>
            <div style="position:relative;margin-bottom:12px">
                <i class="fas fa-search" style="position:absolute;left:12px;top:50%;transform:translateY(-50%);color:#aaa;font-size:13px"></i>
                <input type="text" id="cSearch" placeholder="Search country..." oninput="filterCountries(this.value)"
                    style="width:100%;padding:10px 10px 10px 34px;border:2px solid #e8ecf4;border-radius:10px;font-size:14px;outline:none">
            </div>
            <div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:12px">
                <button type="button" onclick="enableGroup(['BD','IN','PK','SA','AE','MY','KW','QA','OM','BH','JO','IQ'])" style="background:#f0fff4;color:#276749;border:1px solid #c6f6d5;padding:6px 12px;border-radius:8px;font-size:12px;font-weight:600;cursor:pointer">+ Middle East</button>
                <button type="button" onclick="enableGroup(['NG','GH','KE','ZA','EG','ET','CM','SN','UG','TZ'])" style="background:#f0fff4;color:#276749;border:1px solid #c6f6d5;padding:6px 12px;border-radius:8px;font-size:12px;font-weight:600;cursor:pointer">+ Africa</button>
                <button type="button" onclick="enableGroup(['US','GB','CA','AU','DE','FR','IT','ES'])" style="background:#f0fff4;color:#276749;border:1px solid #c6f6d5;padding:6px 12px;border-radius:8px;font-size:12px;font-weight:600;cursor:pointer">+ EU/USA</button>
                <button type="button" onclick="enableGroup(['PH','ID','MY','SG','MM','NP','LK','CN','JP','KR'])" style="background:#f0fff4;color:#276749;border:1px solid #c6f6d5;padding:6px 12px;border-radius:8px;font-size:12px;font-weight:600;cursor:pointer">+ Asia</button>
            </div>
            <div id="countryList" style="max-height:400px;overflow-y:auto;border:2px solid #eee;border-radius:12px">
                <?php if (empty($allCountries)): ?>
                <div style="text-align:center;padding:30px;color:#aaa">No countries found. Sync countries first.</div>
                <?php else: ?>
                <?php foreach ($allCountries as $c): ?>
                <div class="country-row" data-iso="<?= $c['iso'] ?>" data-name="<?= strtolower($c['name']) ?>"
                     style="display:flex;align-items:center;justify-content:space-between;padding:11px 14px;border-bottom:1px solid #f5f5f5">
                    <div style="display:flex;align-items:center;gap:10px">
                        <span style="font-size:18px"><?= isoToFlagAdmin($c['iso']) ?></span>
                        <div>
                            <div style="font-size:13px;font-weight:600;color:#333"><?= htmlspecialchars($c['name']) ?></div>
                            <div style="font-size:11px;color:#aaa"><?= $c['iso'] ?></div>
                        </div>
                    </div>
                    <label style="display:flex;align-items:center;gap:8px;cursor:pointer">
                        <span style="font-size:12px;color:<?= $c['is_enabled']==1?'#38a169':'#aaa' ?>" id="lbl_<?= $c['iso'] ?>"><?= $c['is_enabled']==1?'Enabled':'Disabled' ?></span>
                        <div class="toggle-sw <?= $c['is_enabled']==1?'on':'' ?>" id="tog_<?= $c['iso'] ?>" onclick="toggleCountry('<?= $c['iso'] ?>',this)">
                            <div class="toggle-knob"></div>
                        </div>
                    </label>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>

        <div class="settings-card">
            <div class="settings-title"><i class="fas fa-key" style="color:var(--primary)"></i> DingConnect API Settings</div>            <div class="info-box">
                🔑 <a href="https://www.dingconnect.com" target="_blank">dingconnect.com</a> → Login → <strong>Developer / API Settings</strong> থেকে API Key নিন।
                📖 <a href="https://www.dingconnect.com/Api/Index" target="_blank">API Documentation</a>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="save_settings">
                <div class="form-group">
                    <label><i class="fas fa-key"></i> API Key *</label>
                    <input type="text" name="ding_api_key" value="<?= htmlspecialchars($ding_settings['ding_api_key']??'') ?>" placeholder="আপনার DingConnect API Key">
                </div>
                <div class="form-group">
                    <label>Recharge Mode</label>
                    <div class="mode-toggle">
                        <label class="mode-opt">
                            <input type="radio" name="ding_mode" value="auto" <?= ($ding_settings['ding_mode']??'manual')==='auto'?'checked':'' ?>>
                            <h4>⚡ Auto Mode</h4>
                            <p>User request করলেই সাথে সাথে DingConnect API দিয়ে রিচার্জ হবে</p>
                        </label>
                        <label class="mode-opt">
                            <input type="radio" name="ding_mode" value="manual" <?= ($ding_settings['ding_mode']??'manual')==='manual'?'checked':'' ?>>
                            <h4>🕐 Manual Mode</h4>
                            <p>Pending থাকবে, Admin manually approve করবে</p>
                        </label>
                    </div>
                </div>
                <div class="form-group">
                    <label>
                        <input type="checkbox" name="ding_notify_telegram" value="1" <?= ($ding_settings['ding_notify_telegram']??'1')==='1'?'checked':'' ?> style="width:15px;height:15px;margin-right:6px">
                        Telegram এ Notification পাঠাবে
                    </label>
                </div>
                <div class="btn-group">
                    <button type="submit" class="btn-save"><i class="fas fa-save"></i> সেভ করুন</button>
                    <button type="button" class="btn-test" onclick="testAPI()"><i class="fas fa-plug"></i> Connection Test</button>
                </div>
                <div class="test-result" id="testResult"></div>
            </form>
        </div>

        <!-- Transactions -->
        <div class="txn-table-wrap">
            <!-- Stats bar -->
            <div style="display:grid;grid-template-columns:repeat(5,1fr);border-bottom:2px solid #f5f5f5">
                <?php
                $sBars = [
                    ['Total','📋',$stats['total'],'#555','white'],
                    ['Success','✅',$stats['success'],'#f0fff4','#276749'],
                    ['Pending','⏳',$stats['pending'],'#fffbeb','#d69e2e'],
                    ['Failed','❌',$stats['failed'],'#fff5f5','#c53030'],
                    ['Revenue','💰','৳'.number_format($stats['revenue'],0),'#ebf8ff','#2b6cb0'],
                ];
                foreach($sBars as $sb):
                ?>
                <div style="padding:14px 0;text-align:center;background:<?= $sb[3] ?>;border-right:1px solid #f0f0f0">
                    <div style="font-size:20px;font-weight:800;color:<?= $sb[4] ?>"><?= $sb[2] ?></div>
                    <div style="font-size:11px;color:<?= $sb[4] ?>;opacity:0.7;margin-top:2px"><?= $sb[0] ?></div>
                </div>
                <?php endforeach; ?>
            </div>

            <!-- Today stats -->
            <div style="padding:10px 16px;background:#f8fafc;border-bottom:1px solid #f0f0f0;display:flex;gap:16px;font-size:12px;color:#888">
                <span>📅 Today: <b style="color:#333"><?= $stats['today'] ?></b> requests</span>
                <span>💰 Today revenue: <b style="color:#276749">৳<?= number_format($stats['today_rev'],2) ?></b></span>
                <span>🌍 Intl: <?= $stats['intl_count'] ?> &nbsp; 🔑 PIN: <?= $stats['pin_count'] ?> &nbsp; 🎁 Gift: <?= $stats['gift_count'] ?></span>
            </div>

            <div class="txn-header" style="padding:14px 16px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #f5f5f5">
                <h3 style="font-size:14px;font-weight:800;color:var(--dark);display:flex;align-items:center;gap:6px"><i class="fas fa-exchange-alt" style="color:var(--primary)"></i> Transactions</h3>
                <span style="font-size:12px;color:#aaa"><?= count($txns) ?> records</span>
            </div>

            <!-- Filters -->
            <div style="padding:12px 16px;border-bottom:1px solid #f5f5f5;background:#fafbfc">
                <form method="GET" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
                    <input type="text" name="search" placeholder="User / Phone / Ref..." value="<?= $filterSearch ?>"
                        style="flex:1;min-width:140px;padding:8px 12px;border:2px solid #e8ecf4;border-radius:9px;font-size:12px;outline:none">
                    <select name="type" style="padding:8px 10px;border:2px solid #e8ecf4;border-radius:9px;font-size:12px;outline:none">
                        <option value="">All Types</option>
                        <option value="international" <?= $filterType==='international'?'selected':'' ?>>🌍 Recharge</option>
                        <option value="pin"           <?= $filterType==='pin'?'selected':'' ?>>🔑 PIN</option>
                        <option value="gift"          <?= $filterType==='gift'?'selected':'' ?>>🎁 Gift</option>
                    </select>
                    <select name="status" style="padding:8px 10px;border:2px solid #e8ecf4;border-radius:9px;font-size:12px;outline:none">
                        <option value="">All Status</option>
                        <option value="pending"   <?= $filterStatus==='pending'?'selected':'' ?>>⏳ Pending</option>
                        <option value="success"   <?= $filterStatus==='success'?'selected':'' ?>>✅ Success</option>
                        <option value="failed"    <?= $filterStatus==='failed'?'selected':'' ?>>❌ Failed</option>
                        <option value="refunded"  <?= $filterStatus==='refunded'?'selected':'' ?>>↩️ Refunded</option>
                    </select>
                    <button type="submit" style="padding:8px 14px;background:var(--primary);color:white;border:none;border-radius:9px;font-size:12px;cursor:pointer"><i class="fas fa-search"></i></button>
                </form>
            </div>

            <?php if (empty($txns)): ?>
            <div class="empty" style="padding:40px;text-align:center;color:#ccc"><i class="fas fa-globe" style="font-size:32px;display:block;margin-bottom:8px"></i>No transactions found</div>
            <?php else: ?>
            <?php
            $typeConfig = [
                'international' => ['emoji'=>'🌍','label'=>'Recharge','color'=>'#1a3c8f','bg'=>'#ebf4ff'],
                'pin'           => ['emoji'=>'🔑','label'=>'PIN',     'color'=>'#b7791f','bg'=>'#fffaf0'],
                'gift'          => ['emoji'=>'🎁','label'=>'Gift',    'color'=>'#805ad5','bg'=>'#faf5ff'],
                'card'          => ['emoji'=>'📞','label'=>'Card',    'color'=>'#2c7a7b','bg'=>'#e6fffa'],
            ];
            foreach ($txns as $t):
                $cfg     = $typeConfig[$t['type']] ?? ['emoji'=>'💳','label'=>ucfirst($t['type']),'color'=>'#666','bg'=>'#f5f5f5'];
                $apiData = $t['api_response'] ? json_decode($t['api_response'], true) : null;

                // Extract fail reason
                $failReason = '';
                if(in_array($t['status'],['failed','pending']) && $t['note']) {
                    // DingConnect error codes
                    $note = $t['note'];
                    if(preg_match('/Error:\s*(\w+)/', $note, $m)) $failReason = $m[1];
                    elseif(preg_match('/Failed:\s*(.+?)(\s*\||$)/', $note, $m)) $failReason = trim($m[1]);
                    if($apiData) {
                        $errCodes = $apiData['ErrorCodes'][0]['Code'] ?? '';
                        $errCtx   = $apiData['ErrorCodes'][0]['Context'] ?? '';
                        if($errCodes) $failReason = $errCodes.($errCtx?" ($errCtx)":'');
                    }
                }

                $statusColors = ['success'=>['#f0fff4','#276749'],'pending'=>['#fffbeb','#d69e2e'],'failed'=>['#fff5f5','#c53030'],'refunded'=>['#f5f5f5','#888'],'processing'=>['#ebf8ff','#2b6cb0']];
                $sCl = $statusColors[$t['status']] ?? ['#f5f5f5','#888'];
            ?>
            <div style="border-bottom:1px solid #f5f5f5">
                <!-- Row header -->
                <div onclick="toggleIntl(<?= $t['id'] ?>)" style="display:flex;align-items:center;gap:10px;padding:12px 16px;cursor:pointer;transition:0.15s" onmouseover="this.style.background='#fafbff'" onmouseout="this.style.background=''">
                    <!-- Status icon -->
                    <div style="width:36px;height:36px;border-radius:10px;background:<?= $sCl[0] ?>;display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0">
                        <?= $t['status']==='success'?'✅':($t['status']==='pending'?'⏳':($t['status']==='failed'?'❌':'↩️')) ?>
                    </div>
                    <!-- Info -->
                    <div style="flex:1;min-width:0">
                        <div style="display:flex;align-items:center;gap:6px;margin-bottom:2px">
                            <span style="background:<?= $cfg['bg'] ?>;color:<?= $cfg['color'] ?>;font-size:10px;font-weight:800;padding:2px 8px;border-radius:20px"><?= $cfg['emoji'] ?> <?= $cfg['label'] ?></span>
                            <span style="font-size:13px;font-weight:700;color:#333"><?= htmlspecialchars($t['uname']) ?></span>
                            <?php if($t['phone_number']): ?><span style="font-size:12px;color:#888;font-family:monospace"><?= $t['phone_number'] ?></span><?php endif; ?>
                        </div>
                        <div style="font-size:11px;color:#aaa"><?= $t['reference'] ?> · <?= date('d M y, h:i A',strtotime($t['created_at'])) ?></div>
                        <?php if($failReason): ?>
                        <div style="font-size:11px;color:#c53030;font-weight:600;margin-top:2px">❌ <?= htmlspecialchars($failReason) ?></div>
                        <?php endif; ?>
                    </div>
                    <!-- Amount + status -->
                    <div style="text-align:right;flex-shrink:0">
                        <div style="font-size:16px;font-weight:800;color:var(--primary)"><?= CURRENCY ?><?= number_format($t['amount'],2) ?></div>
                        <span style="font-size:11px;font-weight:700;color:<?= $sCl[1] ?>"><?= ucfirst($t['status']) ?></span>
                    </div>
                    <i class="fas fa-chevron-down" id="ich<?= $t['id'] ?>" style="color:#ddd;font-size:11px;flex-shrink:0;transition:0.2s"></i>
                </div>

                <!-- Expanded detail -->
                <div id="idet<?= $t['id'] ?>" style="display:none;padding:0 16px 14px;background:#fafbff;border-top:1px solid #f0f0f0">
                    <!-- Grid info -->
                    <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin:12px 0">
                        <div style="background:white;border-radius:8px;padding:10px 12px;border:1px solid #f0f0f0">
                            <div style="font-size:10px;color:#aaa;text-transform:uppercase;margin-bottom:3px">Amount</div>
                            <div style="font-size:15px;font-weight:800;color:var(--primary)"><?= CURRENCY ?><?= number_format($t['amount'],2) ?></div>
                        </div>
                        <div style="background:white;border-radius:8px;padding:10px 12px;border:1px solid #f0f0f0">
                            <div style="font-size:10px;color:#aaa;text-transform:uppercase;margin-bottom:3px">Bal Before</div>
                            <div style="font-size:14px;font-weight:700;color:#555"><?= CURRENCY ?><?= number_format($t['balance_before'],2) ?></div>
                        </div>
                        <div style="background:white;border-radius:8px;padding:10px 12px;border:1px solid #f0f0f0">
                            <div style="font-size:10px;color:#aaa;text-transform:uppercase;margin-bottom:3px">Bal After</div>
                            <div style="font-size:14px;font-weight:700;color:#555"><?= CURRENCY ?><?= number_format($t['balance_after'],2) ?></div>
                        </div>
                    </div>

                    <!-- Note -->
                    <?php if($t['note']): ?>
                    <div style="font-size:11px;font-weight:700;color:#888;text-transform:uppercase;margin-bottom:4px">📋 Note / Reason</div>
                    <div style="background:white;border:1px solid #f0f0f0;border-radius:8px;padding:10px 12px;font-size:12px;color:#555;font-family:monospace;margin-bottom:10px;line-height:1.5">
                        <?= htmlspecialchars($t['note']) ?>
                    </div>
                    <?php endif; ?>

                    <!-- API Response -->
                    <?php if($apiData): ?>
                    <div style="font-size:11px;font-weight:700;color:#888;text-transform:uppercase;margin-bottom:4px">📡 API Response</div>
                    <div style="background:#1a1a2e;border-radius:8px;padding:12px;font-size:11px;color:#a8dadc;font-family:monospace;white-space:pre-wrap;max-height:200px;overflow-y:auto;margin-bottom:10px;line-height:1.6">
                        <?= htmlspecialchars(json_encode($apiData, JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE)) ?>
                    </div>
                    <?php endif; ?>

                    <!-- Actions -->
                    <?php if(in_array($t['status'],['pending','processing'])): ?>
                    <div style="display:flex;gap:8px">
                        <button onclick="approveIntl(<?= $t['id'] ?>)" style="padding:9px 16px;background:#f0fff4;color:#276749;border:2px solid #c6f6d5;border-radius:9px;font-size:12px;font-weight:700;cursor:pointer"><i class="fas fa-check"></i> Approve</button>
                        <button onclick="rejectIntl(<?= $t['id'] ?>)" style="padding:9px 16px;background:#fff5f5;color:#c53030;border:2px solid #fed7d7;border-radius:9px;font-size:12px;font-weight:700;cursor:pointer"><i class="fas fa-times"></i> Reject & Refund</button>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
            <?php endif; ?>
        </div>

    </div>
</div>

<script>
function toggleIntl(id) {
    const det = document.getElementById('idet'+id);
    const ch  = document.getElementById('ich'+id);
    const show = det.style.display === 'none' || !det.style.display;
    det.style.display = show ? 'block' : 'none';
    ch.style.transform = show ? 'rotate(180deg)' : '';
}
// Auto-expand pending
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('[id^="idet"]').forEach(function(det) {
        const id = det.id.replace('idet','');
        const row = det.previousElementSibling;
        if(row && row.querySelector('.fa-clock, [style*="⏳"]')) {
            det.style.display = 'block';
            const ch = document.getElementById('ich'+id);
            if(ch) ch.style.transform = 'rotate(180deg)';
        }
    });
});

function toggleCountry(iso, el) {
    const isOn = el.classList.contains('on');
    const newVal = isOn ? 0 : 1;
    el.classList.toggle('on', !isOn);
    const lbl = document.getElementById('lbl_' + iso);
    if (lbl) { lbl.textContent = newVal ? 'Enabled' : 'Disabled'; lbl.style.color = newVal ? '#38a169' : '#aaa'; }
    fetch('international.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'action=toggle_country&iso='+iso+'&enabled='+newVal
    }).then(r=>r.json()).then(d=>{ if(!d.success) { el.classList.toggle('on', isOn); } });
}
function filterCountries(q) {
    document.querySelectorAll('.country-row').forEach(row => {
        const name = row.dataset.name || '';
        const iso  = row.dataset.iso || '';
        row.style.display = (name.includes(q.toLowerCase()) || iso.toLowerCase().includes(q.toLowerCase())) ? '' : 'none';
    });
}
function enableGroup(isos) {
    isos.forEach(iso => {
        const el = document.getElementById('tog_' + iso);
        if (el && !el.classList.contains('on')) toggleCountry(iso, el);
    });
}
function syncCountries() { runSync('sync_countries', ''); }
function syncCountry(iso) { runSync('sync_products', iso); }
function syncAllRegex(btn) {
    const orig = btn.innerHTML;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Starting...';
    btn.disabled = true;
    const res = document.getElementById('syncResult');
    res.style.display='block'; res.style.background='#fffbeb'; res.style.color='#744210';

    // First get list of countries
    fetch('ajax/sync_regex.php')
    .then(r=>r.text()).then(txt=>{
        try {
            const d = JSON.parse(txt);
            if(!d.success){ res.style.background='#fff5f5'; res.style.color='#c53030'; res.textContent='❌ '+d.message; btn.innerHTML=orig; btn.disabled=false; return; }
            const countries = d.countries || [];
            if(!countries.length){ res.textContent='No countries'; btn.innerHTML=orig; btn.disabled=false; return; }
            // Process one by one
            let i=0, total=0;
            function next(){
                if(i>=countries.length){
                    res.style.background='#f0fff4'; res.style.color='#276749';
                    res.textContent='✅ Done! '+total+' products updated across '+countries.length+' countries';
                    btn.innerHTML=orig; btn.disabled=false; return;
                }
                const iso=countries[i++];
                btn.innerHTML='<i class="fas fa-spinner fa-spin"></i> '+iso+' ('+i+'/'+countries.length+')';
                res.textContent='⏳ Processing '+iso+'...';
                fetch('ajax/sync_regex.php?iso='+iso)
                .then(r=>r.json()).then(d=>{ if(d.success) total+=(d.message.match(/\d+/)||[0])[0]*1; next(); })
                .catch(()=>next());
            }
            next();
        } catch(e){ res.style.background='#fff5f5'; res.style.color='#c53030'; res.textContent='❌ '+txt.substring(0,200); btn.innerHTML=orig; btn.disabled=false; }
    }).catch(e=>{ btn.innerHTML=orig; btn.disabled=false; res.style.background='#fff5f5'; res.style.color='#c53030'; res.textContent='❌ Network: '+e; });
}
function syncCustom() {
    const iso = document.getElementById('customCountry').value.trim().toUpperCase();
    if (iso.length !== 2) { alert('2 অক্ষরের ISO code দিন (যেমন: KW)'); return; }
    runSync('sync_products', iso);
}
function updateRate() {
    const rate = document.getElementById('usdRate').value;
    if (!rate) return;
    runSync('update_rate', '', rate);
}
function runSync(action, country, rate) {
    const res = document.getElementById('syncResult');
    res.style.display = 'block';
    res.style.background = '#f0f4ff';
    res.style.color = '#1a3c8f';
    res.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sync হচ্ছে... অপেক্ষা করুন (৩০-১২০ সেকেন্ড লাগতে পারে)';
    const body = new FormData();
    body.append('action', action);
    if (country) body.append('country', country);
    if (rate) body.append('rate', rate);
    fetch('ajax/sync_intl.php', { method: 'POST', body })
    .then(r => r.json())
    .then(d => {
        res.style.background = d.success ? '#f0fff4' : '#fff5f5';
        res.style.color      = d.success ? '#276749' : '#c53030';
        res.innerHTML = d.message;
        if (d.success) setTimeout(() => location.reload(), 1500);
    })
    .catch(() => { res.style.background='#fff5f5'; res.style.color='#c53030'; res.innerHTML='❌ সংযোগ ব্যর্থ!'; });
}
function testAPI() {
    const res = document.getElementById('testResult');
    res.style.display = 'block';
    res.className = 'test-result';
    res.innerHTML = '<i class="fas fa-spinner fa-spin"></i> সংযোগ পরীক্ষা করছি...';
    fetch('ajax/test_ding.php')
        .then(r => r.json())
        .then(d => {
            res.className = 'test-result ' + (d.success ? 'test-ok' : 'test-fail');
            res.innerHTML = d.message;
        })
        .catch(() => { res.className='test-result test-fail'; res.innerHTML='❌ ব্যর্থ হয়েছে!'; });
}
function approveIntl(id) {
    if (!confirm('এই রিচার্জ সফল করবেন?')) return;
    fetch('ajax/intl_action.php', {
        method:'POST', headers:{'Content-Type':'application/json'},
        body: JSON.stringify({action:'success', id})
    }).then(r=>r.json()).then(d=>{ if(d.success) location.reload(); else alert(d.message); });
}
function rejectIntl(id) {
    const note = prompt('রিজেক্টের কারণ:');
    if (note===null) return;
    fetch('ajax/intl_action.php', {
        method:'POST', headers:{'Content-Type':'application/json'},
        body: JSON.stringify({action:'refund', id, note})
    }).then(r=>r.json()).then(d=>{ if(d.success) location.reload(); else alert(d.message); });
}
</script>
</body>
</html>
