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

// Auto-create/fix tables
try {
    $db->exec("CREATE TABLE IF NOT EXISTS drive_packages (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(200) NOT NULL,
        operator_id INT,
        type ENUM('data','voice','combo','sms') DEFAULT 'data',
        data_amount VARCHAR(50),
        voice_minutes VARCHAR(50),
        sms_count VARCHAR(50),
        validity VARCHAR(50),
        api_price DECIMAL(10,2) DEFAULT 0,
        commission_percent DECIMAL(5,2) DEFAULT 0,
        price DECIMAL(10,2) NOT NULL,
        description TEXT,
        status ENUM('active','inactive') DEFAULT 'active',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
    try { $db->exec("ALTER TABLE drive_packages ADD COLUMN api_price DECIMAL(10,2) DEFAULT 0 AFTER validity"); } catch(Exception $e) {}
    // Auto-create drive_requests
    $db->exec("CREATE TABLE IF NOT EXISTS drive_requests (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        package_id INT,
        phone_number VARCHAR(20),
        amount DECIMAL(10,2),
        commission_percent DECIMAL(5,2) DEFAULT 0,
        commission_amount DECIMAL(10,2) DEFAULT 0,
        balance_before DECIMAL(10,2),
        balance_after DECIMAL(10,2),
        reference VARCHAR(50),
        status ENUM('pending','processing','success','failed') DEFAULT 'pending',
        note TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )");
    try { $db->exec("ALTER TABLE drive_packages ADD COLUMN api_price DECIMAL(10,2) DEFAULT 0"); } catch(Exception $ex) {}
    try { $db->exec("ALTER TABLE drive_packages ADD COLUMN cashback_amount DECIMAL(10,2) DEFAULT 0.00"); } catch(Exception $ex2) {}
    try { $db->exec("ALTER TABLE drive_packages ADD COLUMN api_package_id VARCHAR(50) DEFAULT NULL"); } catch(Exception $ex3) {}
} catch(Exception $e) {}

// Per-operator drive API save
if (isset($_POST['action']) && $_POST['action'] === 'save_op_drive_api') {
    $ops = $db->query("SELECT id FROM operators WHERE status='active'")->fetchAll();
    foreach($ops as $op) {
        $apiVal = $_POST['op_drive_api_'.$op['id']] ?? 'ecare';
        $db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")->execute(['op_drive_api_'.$op['id'],$apiVal,$apiVal]);
    }
    $msg = ['ok'=>true,'text'=>'✅ Operator Drive API settings saved!'];
    header('Location: drive_packages.php?ok=1'); exit;
}

// Drive mode setting
if (isset($_POST['action']) && $_POST['action'] === 'save_drive_mode') {
    $mode = $_POST['drive_mode'] ?? 'manual';
    $db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")->execute(['drive_mode',$mode,$mode]);
    $msg = ['ok'=>true,'text'=>'Drive mode saved: '.strtoupper($mode)];
    header('Location: drive_packages.php?ok=1'); exit;
}

// Bulk actions
if (isset($_POST['action']) && $_POST['action'] === 'bulk') {
    $ids    = array_map('intval', $_POST['bulk_ids'] ?? []);
    $bulk   = $_POST['bulk_action'] ?? '';
    if ($ids) {
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        if ($bulk === 'delete') {
            $db->prepare("DELETE FROM drive_packages WHERE id IN ($placeholders)")->execute($ids);
            $msg = ['ok'=>true,'text'=>count($ids).' packages deleted!'];
            header('Location: drive_packages.php?ok=1'); exit;
        } elseif ($bulk === 'active') {
            $db->prepare("UPDATE drive_packages SET status='active' WHERE id IN ($placeholders)")->execute($ids);
            $msg = ['ok'=>true,'text'=>count($ids).' packages activated!'];
            header('Location: drive_packages.php?ok=1'); exit;
        } elseif ($bulk === 'inactive') {
            $db->prepare("UPDATE drive_packages SET status='inactive' WHERE id IN ($placeholders)")->execute($ids);
            $msg = ['ok'=>true,'text'=>count($ids).' packages deactivated!'];
            header('Location: drive_packages.php?ok=1'); exit;
        }
    }
}

// Handle API sync
// Auto sync settings save
if (isset($_POST['action']) && $_POST['action'] === 'save_auto_sync') {
    $pkgSource = $_POST['pkg_source'] ?? 'ecare_direct';
    if ($pkgSource === 'ecare_direct') {
        $api = 'ecare'; $enabled = '0';
        $label = '⚡ ECARE Direct API';
    } elseif ($pkgSource === 'ecare_sync') {
        $api = 'ecare'; $enabled = '1';
        $label = '🔁 ECARE Auto Sync';
    } else {
        $api = 'successtopup'; $enabled = '1';
        $label = '🔄 SuccessTopUp Auto Sync';
    }
    $db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")->execute(['drive_auto_sync',$enabled,$enabled]);
    $db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")->execute(['drive_auto_sync_api',$api,$api]);
    $msg = ['ok'=>true,'text'=>'✅ Package source saved: '.$label];
    header('Location: drive_packages.php?ok=1'); exit;
}

if (isset($_POST['action']) && $_POST['action'] === 'sync_from_api') {
    $syncApi  = $_POST['sync_api']      ?? 'successtopup';
    $operator = $_POST['sync_operator'] ?? '';
    $commPct  = floatval($_POST['sync_commission'] ?? 0);
    $cashbk   = floatval($_POST['sync_cashback']   ?? 0);
    $added = 0; $updated = 0;

    function processDrivePkg($db, $apiId, $apName, $apOp, $apPrice, $apComm, $apValid, $commPct, $cashbk) {
        $titleLower = strtolower($apName);
        if (strpos($titleLower,'min')!==false && strpos($titleLower,'gb')!==false) $apType='combo';
        elseif (strpos($titleLower,'gb')!==false || strpos($titleLower,'mb')!==false) $apType='data';
        elseif (strpos($titleLower,'min')!==false || strpos($titleLower,'poisha')!==false) $apType='voice';
        else $apType='combo';
        preg_match('/(\d+[\.\d]*\s*GB)/i',$apName,$dm);
        preg_match('/(\d+[\.\d]*\s*MIN)/i',$apName,$vm);
        $apData=$dm[1]??''; $apVoice=$vm[1]??'';
        global $db;
        // Better operator lookup — try code first, then name
        $opRow=$db->prepare("SELECT id FROM operators WHERE UPPER(code)=? LIMIT 1");
        $opRow->execute([strtoupper($apOp)]);
        $opId=$opRow->fetchColumn();
        if(!$opId) {
            $opRow2=$db->prepare("SELECT id FROM operators WHERE UPPER(name) LIKE ? LIMIT 1");
            $opRow2->execute(['%'.$apOp.'%']);
            $opId=$opRow2->fetchColumn()?:null;
        }
        $userPrice = $commPct>0 ? round($apPrice-($apPrice*$commPct/100),2) : $apPrice;
        $finalCashbk = $cashbk>0 ? $cashbk : $apComm;
        $exists=$db->prepare("SELECT id FROM drive_packages WHERE api_package_id=?");
        $exists->execute([$apiId]);
        if ($exists->fetchColumn()) {
            $db->prepare("UPDATE drive_packages SET name=?,operator_id=?,type=?,data_amount=?,voice_minutes=?,validity=?,api_price=?,commission_percent=?,price=?,cashback_amount=? WHERE api_package_id=?")
               ->execute([$apName,$opId,$apType,$apData,$apVoice,$apValid,$apPrice,$commPct,$userPrice,$finalCashbk,$apiId]);
            return 'updated';
        } else {
            $db->prepare("INSERT INTO drive_packages (name,operator_id,type,data_amount,voice_minutes,validity,api_price,commission_percent,price,cashback_amount,api_package_id,status) VALUES (?,?,?,?,?,?,?,?,?,?,?,'active')")
               ->execute([$apName,$opId,$apType,$apData,$apVoice,$apValid,$apPrice,$commPct,$userPrice,$finalCashbk,$apiId]);
            return 'added';
        }
    }

    if ($syncApi === 'successtopup') {
        // ST operator codes
        $stOpMap = ['GP'=>'GP','BL'=>'BL','RB'=>'RB','AL'=>'AT','AR'=>'AT','TT'=>'TT','SK'=>'SK'];
        $opList = $operator ? [$operator] : ['GP','BL','RB','AL','TT'];

        // Delete old ST packages before re-syncing
        foreach ($opList as $opCode) {
            $opRow = $db->prepare("SELECT id FROM operators WHERE UPPER(code)=? LIMIT 1");
            $opRow->execute([strtoupper($opCode)]);
            $opId = $opRow->fetchColumn();
            if ($opId) {
                $db->prepare("DELETE FROM drive_packages WHERE operator_id=? AND (api_package_id NOT LIKE 'ECARE_%') AND api_package_id IS NOT NULL")->execute([$opId]);
            }
        }

        foreach ($opList as $opCode) {
            $stCode = $stOpMap[strtoupper($opCode)] ?? strtoupper($opCode);
            $apiResult = successTopupDriveList($stCode);

            // ST response can be: {result:1, drives:[...]} or {result:1, data:[...]} or {result:true, packages:[...]}
            $drives = $apiResult['drives'] ?? $apiResult['data'] ?? $apiResult['packages'] ?? [];

            // Sometimes result is nested: {result:1, result:{drives:[...]}}
            if (empty($drives) && !empty($apiResult['result']) && is_array($apiResult['result'])) {
                $drives = $apiResult['result']['drives'] ?? $apiResult['result']['data'] ?? [];
            }

            if (empty($drives)) {
                // Log raw response for debugging
                $msg = ['ok'=>false,'text'=>'ST API response for '.$opCode.': '.json_encode(array_slice((array)$apiResult,0,5))];
                continue;
            }

            foreach ($drives as $ap) {
                if (!is_array($ap)) continue;
                $apiId   = strval($ap['driveId'] ?? $ap['id'] ?? $ap['package_id'] ?? '');
                $apName  = preg_replace('/\s*-\s*\(ALL BD\)\s*$/i', '', trim($ap['title'] ?? $ap['name'] ?? $ap['package_name'] ?? 'Package'));
                $apOp    = strtoupper($ap['operator'] ?? $opCode);
                // Map ST codes back to our codes
                $revMap = ['AT'=>'AL','RB'=>'RB','GP'=>'GP','BL'=>'BL','TT'=>'TT','SK'=>'SK'];
                $apOp   = $revMap[$apOp] ?? $apOp;
                $apPrice = floatval($ap['price'] ?? $ap['amount'] ?? 0);
                $apComm  = floatval($ap['commission'] ?? $ap['cashback'] ?? 0);
                $apValid = ($ap['duration'] ?? $ap['validity'] ?? '30').' Days';
                if (!$apiId || !$apPrice) continue;
                $r = processDrivePkg($db,$apiId,$apName,$apOp,$apPrice,$apComm,$apValid,$commPct,$cashbk);
                if ($r==='added') $added++; else $updated++;
            }
        }
        $msg = ['ok'=>true,'text'=>"✅ SuccessTopUp Sync done! Added: $added, Updated: $updated"];
        header('Location: drive_packages.php?ok=1'); exit;

    } elseif ($syncApi === 'ecare') {
        $opList = $operator ? [$operator] : ['GP','BL','RB','AL','TT'];
        // Delete old ECARE packages for these operators
        foreach ($opList as $opCode) {
            $opRow = $db->prepare("SELECT id FROM operators WHERE UPPER(code)=? LIMIT 1");
            $opRow->execute([strtoupper($opCode)]);
            $opId = $opRow->fetchColumn();
            if ($opId) {
                $db->prepare("DELETE FROM drive_packages WHERE operator_id=? AND api_package_id LIKE 'ECARE_%'")->execute([$opId]);
            }
        }
        foreach ($opList as $opCode) {
            $res = ecareOfferPacks($opCode);
            if (empty($res['STATUS']) || $res['STATUS'] !== 'OK') continue;

            // Data is in $res[$opCode] array
            $items = $res[$opCode] ?? $res['packages'] ?? [];
            if (!is_array($items)) continue;

            foreach ($items as $idx => $ap) {
                if (!is_array($ap)) continue;

                $apOp     = $ap['_operator'] ?? $opCode;
                $apPrice  = floatval($ap['_amount'] ?? 0);
                $apComm   = floatval(str_replace(',','',$ap['_commission_amount'] ?? 0));
                $apValid  = $ap['_validity'] ?? '30 Days';
                $apData   = $ap['_internet_pack'] ?? '';
                $apVoice  = $ap['_minute_pack'] ?? '';
                $apStatus = $ap['_status'] ?? 'A';
                $numType  = $ap['_number_type'] ?? '1';

                if ($apStatus !== 'A') continue; // skip inactive
                if (!$apPrice) continue;

                // Build name
                $nameParts = [];
                if ($apData && $apData !== '-') $nameParts[] = $apData;
                if ($apVoice && $apVoice !== '-') $nameParts[] = $apVoice.' Min';
                if (empty($nameParts)) $nameParts[] = '৳'.$apPrice.' Pack';
                $apName = implode(' + ', $nameParts).' ('.$apValid.')';

                // Type
                $hasData  = ($apData && $apData !== '-');
                $hasVoice = ($apVoice && $apVoice !== '-');
                $apType   = ($hasData && $hasVoice) ? 'combo' : ($hasData ? 'data' : 'voice');

                // Unique ID
                $apiId = 'ECARE_'.$opCode.'_'.$idx.'_'.intval($apPrice);

                $opRow = $db->prepare("SELECT id FROM operators WHERE UPPER(code)=? OR UPPER(name) LIKE ? LIMIT 1");
                $opRow->execute([strtoupper($apOp),'%'.$apOp.'%']); $opId=$opRow->fetchColumn()?:null;
                $userPrice   = $commPct>0 ? round($apPrice-($apPrice*$commPct/100),2) : $apPrice;
                $finalCashbk = $cashbk>0 ? $cashbk : $apComm;

                $exists = $db->prepare("SELECT id FROM drive_packages WHERE api_package_id=?");
                $exists->execute([$apiId]);
                if ($exists->fetchColumn()) {
                    $db->prepare("UPDATE drive_packages SET name=?,operator_id=?,type=?,data_amount=?,voice_minutes=?,validity=?,api_price=?,commission_percent=?,price=?,cashback_amount=? WHERE api_package_id=?")
                       ->execute([$apName,$opId,$apType,$apData,$apVoice,$apValid,$apPrice,$commPct,$userPrice,$finalCashbk,$apiId]);
                    $updated++;
                } else {
                    $db->prepare("INSERT INTO drive_packages (name,operator_id,type,data_amount,voice_minutes,validity,api_price,commission_percent,price,cashback_amount,api_package_id,status) VALUES (?,?,?,?,?,?,?,?,?,?,?,'active')")
                       ->execute([$apName,$opId,$apType,$apData,$apVoice,$apValid,$apPrice,$commPct,$userPrice,$finalCashbk,$apiId]);
                    $added++;
                }
            }
        }
        $msg = ['ok'=>true,'text'=>"✅ ECARE Sync done! Added: $added, Updated: $updated"];
        header('Location: drive_packages.php?ok=1'); exit;
    }
    // Save last sync time
    $db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")->execute(['drive_last_sync',date('Y-m-d H:i:s'),date('Y-m-d H:i:s')]);
}

$msg = $msg ?? null;

$msg = null;
if (isset($_GET['ok'])) $msg = ['ok'=>true,'text'=>'✅ Saved!'];

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

    if ($action === 'add' || $action === 'edit') {
        $name    = trim($_POST['name'] ?? '');
        $opId    = intval($_POST['operator_id'] ?? 0);
        $type    = $_POST['type'] ?? 'data';
        $data    = trim($_POST['data_amount'] ?? '');
        $voice   = trim($_POST['voice_minutes'] ?? '');
        $sms     = trim($_POST['sms_count'] ?? '');
        $valid   = trim($_POST['validity'] ?? '');
        $apiPrc  = floatval($_POST['api_price'] ?? 0);
        $commPct = floatval($_POST['commission_percent'] ?? 0);
        // User price = api_price - commission%
        $userPrc = $apiPrc > 0
            ? round($apiPrc - ($apiPrc * $commPct / 100), 2)
            : floatval($_POST['price'] ?? 0);
        $desc    = trim($_POST['description'] ?? '');
        $cashbk  = floatval($_POST['cashback_amount'] ?? 0);
        $status  = $_POST['status'] ?? 'active';

        if (!$name) { $msg = ['ok'=>false,'text'=>'Package name required!']; }
        else {
            if ($action === 'add') {
                $db->prepare("INSERT INTO drive_packages (name,operator_id,type,data_amount,voice_minutes,sms_count,validity,api_price,commission_percent,price,cashback_amount,description,status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)")
                   ->execute([$name,$opId,$type,$data,$voice,$sms,$valid,$apiPrc,$commPct,$userPrc,$cashbk,$desc,$status]);
                $msg = ['ok'=>true,'text'=>"Package '$name' added! Price: ৳$userPrc, Cashback: ৳$cashbk"];
                header('Location: drive_packages.php?ok=1'); exit;
            } else {
                $id = intval($_POST['id']);
                $db->prepare("UPDATE drive_packages SET name=?,operator_id=?,type=?,data_amount=?,voice_minutes=?,sms_count=?,validity=?,api_price=?,commission_percent=?,price=?,cashback_amount=?,description=?,status=? WHERE id=?")
                   ->execute([$name,$opId,$type,$data,$voice,$sms,$valid,$apiPrc,$commPct,$userPrc,$cashbk,$desc,$status,$id]);
                $msg = ['ok'=>true,'text'=>"Updated! Price: ৳$userPrc, Cashback: ৳$cashbk"];
                header('Location: drive_packages.php?ok=1'); exit;
            }
        }
    }
    if ($action === 'toggle') {
        $id = intval($_POST['id']);
        $db->prepare("UPDATE drive_packages SET status=CASE WHEN status='active' THEN 'inactive' ELSE 'active' END WHERE id=?")->execute([$id]);
        $msg = ['ok'=>true,'text'=>'Status changed!'];
        header('Location: drive_packages.php?ok=1'); exit;
    }
    if ($action === 'delete') {
        $db->prepare("DELETE FROM drive_packages WHERE id=?")->execute([intval($_POST['id'])]);
        $msg = ['ok'=>true,'text'=>'Deleted!'];
        header('Location: drive_packages.php?ok=1'); exit;
    }
}

$operators   = $db->query("SELECT * FROM operators WHERE status='active' ORDER BY name")->fetchAll();
$drive_mode  = getSetting('drive_mode') ?: 'manual';
$filterOp    = intval($_GET['op'] ?? 0);
$filterOpName = $_GET['opname'] ?? '';
$pkgWhere  = $filterOp ? "WHERE dp.operator_id=$filterOp" : "";
$packages  = $db->query("SELECT dp.*, o.name as op_name FROM drive_packages dp LEFT JOIN operators o ON dp.operator_id=o.id $pkgWhere ORDER BY dp.status DESC, dp.operator_id, dp.price")->fetchAll();
// Operators with package count
$opGroups  = $db->query("SELECT o.id, o.name, COUNT(dp.id) as pkg_count FROM operators o LEFT JOIN drive_packages dp ON dp.operator_id=o.id AND dp.status='active' GROUP BY o.id ORDER BY o.name")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Drive Packages - 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>
.card{background:white;border-radius:12px;box-shadow:0 2px 8px rgba(0,0,0,0.05);margin-bottom:18px;overflow:hidden}
.card-h{padding:14px 18px;border-bottom:1px solid #f5f5f5;font-size:14px;font-weight:700;color:var(--dark);display:flex;align-items:center;gap:8px}
.card-b{padding:18px}
.alert{padding:11px 16px;border-radius:10px;font-size:13px;font-weight:600;margin-bottom:14px}
.alert-ok{background:#f0fff4;color:#276749;border:1px solid #c6f6d5}
.alert-err{background:#fff5f5;color:#c53030;border:1px solid #fed7d7}
.frow{display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:10px;margin-bottom:12px}
.fg{display:flex;flex-direction:column;gap:4px}
.fg label{font-size:12px;font-weight:600;color:#555}
.fg input,.fg select,.fg textarea{padding:9px 11px;border:2px solid #e8ecf4;border-radius:9px;font-size:13px;outline:none;width:100%}
.fg input:focus,.fg select:focus{border-color:var(--primary)}
.price-preview{background:#f0fff4;border-radius:10px;padding:12px 16px;margin-bottom:12px;display:none}
.price-preview .pp-row{display:flex;justify-content:space-between;font-size:13px;padding:4px 0}
.price-preview .pp-final{font-size:18px;font-weight:800;color:#276749}
.btn{padding:9px 16px;border:none;border-radius:9px;font-size:13px;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:6px}
.btn-primary{background:var(--primary);color:white}
.btn-sm{padding:5px 11px;font-size:12px;border-radius:7px;cursor:pointer;border:none;font-weight:600}
.btn-edit{background:#ebf8ff;color:#2b6cb0}
.btn-del{background:#fff5f5;color:#e53e3e}
table{width:100%;border-collapse:collapse}
th{padding:9px 12px;text-align:left;font-size:11px;color:#888;font-weight:700;text-transform:uppercase;border-bottom:2px solid #f5f5f5;white-space:nowrap}
td{padding:10px 12px;border-bottom:1px solid #f9f9f9;font-size:13px;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}
.b-act{background:#f0fff4;color:#276749}.b-in{background:#fff5f5;color:#e53e3e}
.type-badge{padding:3px 9px;border-radius:20px;font-size:11px;font-weight:700}
.modal-ov{display:none;position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:9999;align-items:center;justify-content:center}
.modal-ov.show{display:flex}
.modal-box{background:white;border-radius:14px;padding:22px;width:94%;max-width:580px;max-height:90vh;overflow-y:auto}
.modal-box h3{font-size:16px;font-weight:800;margin-bottom:16px;color:var(--dark)}
.gap-btn{display:flex;gap:8px;margin-top:14px}
</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>
        <span class="topbar-title">⚡ Drive Packages</span>
    </div>
    <div class="topbar-right">
        <button class="btn btn-primary" onclick="openAdd()"><i class="fas fa-plus"></i> Add Package</button>
    </div>
</div>

<div class="content">
<?php if($msg): ?>
<div class="alert <?= $msg['ok']?'alert-ok':'alert-err' ?>"><?= $msg['ok']?'✅':'❌' ?> <?= htmlspecialchars($msg['text']) ?></div>
<?php endif; ?>

<!-- Drive Settings -->
<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:14px;margin-bottom:18px">

    <!-- Drive Mode -->
    <div class="card" style="margin-bottom:0">
        <div class="card-h"><i class="fas fa-cog" style="color:#805ad5"></i> Drive Mode</div>
        <div class="card-b">
            <form method="POST">
                <input type="hidden" name="action" value="save_drive_mode">
                <div style="display:flex;flex-direction:column;gap:8px;margin-bottom:14px">
                    <label style="display:flex;align-items:center;gap:10px;padding:11px;border-radius:10px;border:2px solid <?= $drive_mode==='auto'?'#38a169':'#e8ecf4' ?>;cursor:pointer;background:<?= $drive_mode==='auto'?'#f0fff4':'white' ?>">
                        <input type="radio" name="drive_mode" value="auto" <?= $drive_mode==='auto'?'checked':'' ?> style="width:16px;height:16px">
                        <div>
                            <div style="font-size:13px;font-weight:700">⚡ Auto Mode</div>
                            <div style="font-size:11px;color:#888">API তে সরাসরি submit</div>
                        </div>
                    </label>
                    <label style="display:flex;align-items:center;gap:10px;padding:11px;border-radius:10px;border:2px solid <?= $drive_mode==='manual'?'#3182ce':'#e8ecf4' ?>;cursor:pointer;background:<?= $drive_mode==='manual'?'#ebf8ff':'white' ?>">
                        <input type="radio" name="drive_mode" value="manual" <?= $drive_mode==='manual'?'checked':'' ?> style="width:16px;height:16px">
                        <div>
                            <div style="font-size:13px;font-weight:700">🖐 Manual Mode</div>
                            <div style="font-size:11px;color:#888">Admin approve করবে</div>
                        </div>
                    </label>
                </div>
                <button type="submit" class="btn btn-primary" style="width:100%;justify-content:center"><i class="fas fa-save"></i> Save</button>
            </form>
        </div>
    </div>

    <!-- Package Source -->
    <div class="card" style="margin-bottom:0">
        <?php
        $autoSyncApi = getSetting('drive_auto_sync_api') ?: 'ecare';
        $autoSync    = getSetting('drive_auto_sync') ?: '0';
        $lastSync    = getSetting('drive_last_sync') ?: '';
        ?>
        <div class="card-h"><i class="fas fa-plug" style="color:#e67e22"></i> Package Source</div>
        <div class="card-b">
            <form method="POST" style="margin-bottom:12px">
                <input type="hidden" name="action" value="save_auto_sync">
                <input type="hidden" name="auto_sync_enabled" id="autoSyncEnabled" value="<?= $autoSync ?>">
                <div style="display:flex;flex-direction:column;gap:8px;margin-bottom:12px">

                    <!-- ECARE Direct -->
                    <label style="display:flex;align-items:center;gap:10px;padding:11px;border-radius:10px;border:2px solid <?= ($autoSyncApi==='ecare'&&$autoSync!=='1')?'#e67e22':'#e8ecf4' ?>;cursor:pointer;background:<?= ($autoSyncApi==='ecare'&&$autoSync!=='1')?'#fff8f0':'white' ?>">
                        <input type="radio" name="pkg_source" value="ecare_direct"
                            <?= ($autoSyncApi==='ecare'&&$autoSync!=='1')?'checked':'' ?>
                            style="width:16px;height:16px"
                            onchange="setPkgSource('ecare_direct')">
                        <div>
                            <div style="font-size:13px;font-weight:700">⚡ ECARE Direct</div>
                            <div style="font-size:11px;color:#888">Real-time API — DB save নেই</div>
                        </div>
                    </label>

                    <!-- ECARE Auto Sync -->
                    <label style="display:flex;align-items:center;gap:10px;padding:11px;border-radius:10px;border:2px solid <?= ($autoSyncApi==='ecare'&&$autoSync==='1')?'#38a169':'#e8ecf4' ?>;cursor:pointer;background:<?= ($autoSyncApi==='ecare'&&$autoSync==='1')?'#f0fff4':'white' ?>">
                        <input type="radio" name="pkg_source" value="ecare_sync"
                            <?= ($autoSyncApi==='ecare'&&$autoSync==='1')?'checked':'' ?>
                            style="width:16px;height:16px"
                            onchange="setPkgSource('ecare_sync')">
                        <div>
                            <div style="font-size:13px;font-weight:700">🔁 ECARE Auto Sync</div>
                            <div style="font-size:11px;color:#888">Every 10 min DB sync<?= $lastSync&&$autoSyncApi==='ecare'?' · '.date('h:i A',strtotime($lastSync)):'' ?></div>
                        </div>
                    </label>

                    <!-- SuccessTopUp Auto Sync -->
                    <label style="display:flex;align-items:center;gap:10px;padding:11px;border-radius:10px;border:2px solid <?= ($autoSyncApi==='successtopup'&&$autoSync==='1')?'#3182ce':'#e8ecf4' ?>;cursor:pointer;background:<?= ($autoSyncApi==='successtopup'&&$autoSync==='1')?'#ebf8ff':'white' ?>">
                        <input type="radio" name="pkg_source" value="st_sync"
                            <?= ($autoSyncApi==='successtopup'&&$autoSync==='1')?'checked':'' ?>
                            style="width:16px;height:16px"
                            onchange="setPkgSource('st_sync')">
                        <div>
                            <div style="font-size:13px;font-weight:700">🔄 SuccessTopUp Sync</div>
                            <div style="font-size:11px;color:#888">Every 10 min DB sync<?= $lastSync&&$autoSyncApi==='successtopup'?' · '.date('h:i A',strtotime($lastSync)):'' ?></div>
                        </div>
                    </label>

                </div>
                <input type="hidden" name="auto_sync_api" id="autoSyncApi" value="<?= $autoSyncApi ?>">
                <button type="submit" class="btn btn-primary" style="width:100%;justify-content:center;margin-bottom:8px"><i class="fas fa-save"></i> Save</button>
            </form>

            <!-- Sync Now -->
            <form method="POST">
                <input type="hidden" name="action" value="sync_from_api">
                <input type="hidden" name="sync_api" id="syncNowApi" value="<?= $autoSyncApi ?>">
                <input type="hidden" name="sync_operator" value="">
                <input type="hidden" name="sync_commission" value="0">
                <input type="hidden" name="sync_cashback" value="0">
                <button type="submit" class="btn" style="width:100%;background:#38a169;color:white;justify-content:center"><i class="fas fa-sync"></i> Sync Now</button>
            </form>
        </div>
    </div>

    <!-- Per-Operator API -->
    <div class="card" style="margin-bottom:0">
        <div class="card-h"><i class="fas fa-sliders-h" style="color:#3182ce"></i> Operator API</div>
        <div class="card-b" style="padding:12px">
            <form method="POST">
                <input type="hidden" name="action" value="save_op_drive_api">
                <div style="font-size:11px;color:#aaa;margin-bottom:10px">কোন Operator এর Drive কোন API দিয়ে যাবে</div>
                <?php
                $opColors = ['GP'=>'#009B3A','BL'=>'#FF6B00','RB'=>'#E4001D','AL'=>'#F7941D','TT'=>'#1C3F7A'];
                foreach($operators as $op):
                    if(in_array($op['code'],['DING','BT'])) continue;
                    $currentApi = getSetting('op_drive_api_'.$op['id']) ?: 'ecare';
                    $color = $opColors[strtoupper($op['code'])] ?? '#1a3c8f';
                ?>
                <div style="display:flex;align-items:center;gap:8px;padding:7px 0;border-bottom:1px solid #f5f5f5">
                    <div style="width:8px;height:8px;border-radius:50%;background:<?= $color ?>;flex-shrink:0"></div>
                    <span style="font-size:12px;font-weight:700;flex:1"><?= htmlspecialchars($op['name']) ?></span>
                    <select name="op_drive_api_<?= $op['id'] ?>" style="font-size:11px;padding:4px 6px;border:1px solid #e8ecf4;border-radius:6px;outline:none;color:#333">
                        <option value="ecare"        <?= $currentApi==='ecare'?'selected':'' ?>>⚡ ECARE</option>
                        <option value="successtopup" <?= $currentApi==='successtopup'?'selected':'' ?>>🔄 ST</option>
                        <option value="manual"       <?= $currentApi==='manual'?'selected':'' ?>>🖐 Manual</option>
                    </select>
                </div>
                <?php endforeach; ?>
                <button type="submit" class="btn btn-primary" style="width:100%;justify-content:center;margin-top:12px"><i class="fas fa-save"></i> Save</button>
            </form>
        </div>
    </div>

</div>

<!-- Quick Stats -->
<div style="background:linear-gradient(135deg,#0d1f4e,#1a3c8f);border-radius:14px;padding:16px 20px;color:white;margin-bottom:18px;display:flex;gap:0;text-align:center">
    <?php
    $totalPkgs  = count($packages);
    $activePkgs = count(array_filter($packages,fn($p)=>$p['status']==='active'));
    $stats = [
        ['📦','Total',$totalPkgs],
        ['✅','Active',$activePkgs],
        ['❌','Inactive',$totalPkgs-$activePkgs],
        ['📡','Operators',count($operators)],
    ];
    foreach($stats as $s): ?>
    <div style="flex:1;border-right:1px solid rgba(255,255,255,0.1);padding:8px 0">
        <div style="font-size:22px;font-weight:800"><?= $s[2] ?></div>
        <div style="font-size:11px;opacity:0.6;margin-top:2px"><?= $s[0] ?> <?= $s[1] ?></div>
    </div>
    <?php endforeach; ?>
</div>

<!-- Operator Tabs -->
<div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:14px">
    <a href="drive_packages.php" class="btn <?= !$filterOp?'btn-primary':'' ?>" style="<?= $filterOp?'background:#f5f5f5;color:#555':'' ?>;font-size:12px;padding:7px 14px">
        All (<?= count($packages) ?>)
    </a>
    <?php foreach($opGroups as $og): if(!$og['pkg_count']) continue; ?>
    <a href="?op=<?= $og['id'] ?>" class="btn" style="background:<?= $filterOp==$og['id']?'var(--primary)':'#f5f5f5' ?>;color:<?= $filterOp==$og['id']?'white':'#555' ?>;font-size:12px;padding:7px 14px">
        <?= htmlspecialchars($og['name']) ?> (<?= $og['pkg_count'] ?>)
    </a>
    <?php endforeach; ?>
</div>

<!-- Package List -->
<div class="card">
    <div class="card-h" style="justify-content:space-between">
        <span><i class="fas fa-list"></i> Drive Packages (<?= count($packages) ?>)</span>
        <div style="display:flex;gap:8px;align-items:center">
            <select id="bulkAction" style="padding:6px 10px;border:2px solid #e8ecf4;border-radius:8px;font-size:12px;outline:none">
                <option value="">Bulk Action</option>
                <option value="active">✅ Activate</option>
                <option value="inactive">❌ Deactivate</option>
                <option value="delete">🗑 Delete</option>
            </select>
            <button onclick="applyBulk()" class="btn" style="background:#e53e3e;color:white;font-size:12px;padding:7px 12px"><i class="fas fa-check"></i> Apply</button>
        </div>
    </div>
    <?php if(empty($packages)): ?>
    <div style="text-align:center;padding:40px;color:#aaa"><i class="fas fa-box-open" style="font-size:30px;display:block;margin-bottom:10px"></i>No packages yet. Add your first package!</div>
    <?php else: ?>

    <!-- Bulk action bar (outside table) -->
    <div style="display:flex;gap:8px;align-items:center;padding:10px 0;flex-wrap:wrap">
        <label style="display:flex;align-items:center;gap:6px;font-size:13px;font-weight:600;cursor:pointer">
            <input type="checkbox" id="selAll" onchange="toggleAll(this)" style="width:16px;height:16px"> Select All
        </label>
        <select id="bulkAction" style="padding:7px 10px;border:2px solid #e8ecf4;border-radius:8px;font-size:12px;outline:none">
            <option value="">Bulk Action</option>
            <option value="active">✅ Activate</option>
            <option value="inactive">❌ Deactivate</option>
            <option value="delete">🗑 Delete</option>
        </select>
        <button onclick="applyBulk()" type="button" class="btn" style="background:#e53e3e;color:white;font-size:12px;padding:7px 14px"><i class="fas fa-check"></i> Apply</button>
        <span id="selCount" style="font-size:12px;color:#aaa"></span>
    </div>

    <form method="POST" id="bulkForm">
        <input type="hidden" name="action" value="bulk">
        <input type="hidden" name="bulk_action" id="bulkActionVal">
        <!-- Hidden checkboxes will be added by JS -->
        <div id="hiddenIds"></div>
    </form>

    <div style="overflow-x:auto">
    <table>
        <thead><tr>
            <th style="width:30px"></th>
            <th>Package</th><th>Operator</th><th>Type</th>
            <th>Details</th><th>User Price</th><th>💰 Cashback</th>
            <th>Validity</th><th>Status</th><th>Action</th>
        </tr></thead>
        <tbody>
        <?php foreach($packages as $p): 
            $typeColors = ['data'=>'#3182ce','voice'=>'#38a169','combo'=>'#805ad5','sms'=>'#d69e2e'];
            $typeIcons  = ['data'=>'📶','voice'=>'📞','combo'=>'⚡','sms'=>'💬'];
            $tc = $typeColors[$p['type']]??'#718096';
        ?>
        <tr>
            <td><input type="checkbox" class="row-cb" data-id="<?= $p['id'] ?>" onchange="updateSelCount()" style="width:16px;height:16px"></td>
            <td><strong><?= htmlspecialchars($p['name']) ?></strong></td>
            <td><?= htmlspecialchars($p['op_name']??'-') ?></td>
            <td><span class="type-badge" style="background:<?= $tc ?>22;color:<?= $tc ?>"><?= $typeIcons[$p['type']]??'📦' ?> <?= ucfirst($p['type']) ?></span></td>
            <td style="font-size:12px;color:#666">
                <?= $p['data_amount'] ? '📶 '.$p['data_amount'] : '' ?>
                <?= $p['voice_minutes'] ? ' 📞 '.$p['voice_minutes'].'min' : '' ?>
                <?= $p['sms_count'] ? ' 💬 '.$p['sms_count'] : '' ?>
            </td>
            <td><strong style="color:var(--primary);font-size:15px"><?= CURRENCY ?><?= number_format($p['price'],2) ?></strong></td>
            <td><?= floatval($p['cashback_amount']??0)>0 ? '<span style="background:#f0fff4;color:#276749;padding:3px 10px;border-radius:20px;font-size:12px;font-weight:700">+'.CURRENCY.number_format($p['cashback_amount'],0).'</span>' : '<span style="color:#ddd">—</span>' ?></td>
            <td style="font-size:12px"><?= $p['validity']?:'-' ?></td>
            <td>
                <form method="POST" style="display:inline">
                    <input type="hidden" name="action" value="toggle">
                    <input type="hidden" name="id" value="<?= $p['id'] ?>">
                    <button type="submit" class="badge <?= $p['status']==='active'?'b-act':'b-in' ?>" style="border:none;cursor:pointer">
                        <?= $p['status']==='active'?'✅ Active':'❌ Inactive' ?>
                    </button>
                </form>
            </td>
            <td>
                <div style="display:flex;gap:5px">
                    <button class="btn-sm btn-edit" onclick='openEdit(<?= htmlspecialchars(json_encode($p),ENT_QUOTES) ?>)'>
                        <i class="fas fa-edit"></i> Edit
                    </button>
                    <form method="POST" onsubmit="return confirm('Delete?')" style="display:inline">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="id" value="<?= $p['id'] ?>">
                        <button type="submit" class="btn-sm btn-del"><i class="fas fa-trash"></i></button>
                    </form>
                </div>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>
    <?php endif; ?>
</div>

</div><!-- content -->
</div><!-- main -->

<!-- Add/Edit Modal -->
<div class="modal-ov" id="pkgModal" onclick="if(event.target===this)closeModal()">
<div class="modal-box">
    <h3 id="modalTitle"><i class="fas fa-plus-circle" style="color:var(--primary)"></i> Add Drive Package</h3>
    <form method="POST" id="pkgForm">
        <input type="hidden" name="action" id="formAction" value="add">
        <input type="hidden" name="id" id="formId">

        <div class="frow">
            <div class="fg" style="grid-column:1/-1">
                <label>Package Name *</label>
                <input name="name" id="fName" placeholder="e.g. GP 1GB 7 Days" required>
            </div>
            <div class="fg">
                <label>Operator</label>
                <select name="operator_id" id="fOp">
                    <option value="">Select Operator</option>
                    <?php foreach($operators as $o): ?>
                    <option value="<?= $o['id'] ?>"><?= htmlspecialchars($o['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="fg">
                <label>Type</label>
                <select name="type" id="fType">
                    <option value="data">📶 Data</option>
                    <option value="voice">📞 Voice</option>
                    <option value="combo">⚡ Combo</option>
                    <option value="sms">💬 SMS</option>
                </select>
            </div>
        </div>

        <div class="frow">
            <div class="fg">
                <label>Data Amount</label>
                <input name="data_amount" id="fData" placeholder="e.g. 1GB, 500MB">
            </div>
            <div class="fg">
                <label>Voice Minutes</label>
                <input name="voice_minutes" id="fVoice" placeholder="e.g. 100 Min">
            </div>
            <div class="fg">
                <label>SMS</label>
                <input name="sms_count" id="fSms" placeholder="e.g. 50 SMS">
            </div>
            <div class="fg">
                <label>Validity</label>
                <input name="validity" id="fValidity" placeholder="e.g. 7 Days">
            </div>
        </div>

        <!-- Price Section -->
        <div style="background:#f8fafc;border-radius:12px;padding:14px;margin-bottom:12px;border:2px solid #e8ecf4">
            <div style="font-size:12px;font-weight:700;color:#555;margin-bottom:10px;text-transform:uppercase">💰 Pricing</div>
            <div class="frow">
                <div class="fg">
                    <label>API Price (৳)</label>
                    <input type="number" name="api_price" id="fApiPrice" step="0.01" min="0" placeholder="Original price" oninput="calcPrice()">
                </div>
                <div class="fg">
                    <label>Commission % (discount)</label>
                    <input type="number" name="commission_percent" id="fComm" step="0.01" min="0" max="100" placeholder="e.g. 2" oninput="calcPrice()">
                </div>
                <div class="fg">
                    <label>User Price (৳) — auto</label>
                    <input type="number" name="price" id="fPrice" step="0.01" min="0" placeholder="Auto calculated" style="background:#f0fff4;font-weight:700;color:#276749">
                </div>
            </div>
            <!-- Price Preview -->
            <div class="price-preview" id="pricePreview">
                <div class="pp-row"><span>API Price</span><span id="ppApi"></span></div>
                <div class="pp-row" style="color:#38a169"><span>Commission Discount</span><span id="ppDisc"></span></div>
                <div style="border-top:1px solid #c6f6d5;margin:6px 0"></div>
                <div class="pp-row"><span style="font-weight:700">User Pays</span><span class="pp-final" id="ppFinal"></span></div>
            </div>
        </div>

        <div class="frow">
            <div class="fg" style="grid-column:1/-1">
                <label>Description (optional)</label>
                <input name="description" id="fDesc" placeholder="Package details...">
            </div>
            <div class="fg">
                <label>Status</label>
                <select name="status" id="fStatus">
                    <option value="active">✅ Active</option>
                    <option value="inactive">❌ Inactive</option>
                </select>
            </div>
        </div>

        <div style="background:#f0fff4;border-radius:10px;padding:12px 14px;margin-bottom:12px;border:2px solid #c6f6d5">
            <div style="font-size:12px;font-weight:700;color:#276749;margin-bottom:8px">💰 Cashback (After Purchase Success)</div>
            <div class="fg" style="margin-bottom:0">
                <label>Cashback Amount (৳) — added to user balance on success</label>
                <input type="number" name="cashback_amount" id="fCashback" step="0.01" min="0" placeholder="e.g. 20" value="0">
            </div>
        </div>
        <div class="gap-btn">
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save Package</button>
            <button type="button" class="btn" style="background:#f5f5f5" onclick="closeModal()">Cancel</button>
        </div>
    </form>
</div>
</div>

<script>
function calcPrice() {
    const api  = parseFloat(document.getElementById('fApiPrice').value) || 0;
    const comm = parseFloat(document.getElementById('fComm').value) || 0;
    if (api > 0) {
        const disc  = api * comm / 100;
        const final = Math.round((api - disc) * 100) / 100;
        document.getElementById('fPrice').value = final.toFixed(2);
        document.getElementById('ppApi').textContent   = '৳' + api.toFixed(2);
        document.getElementById('ppDisc').textContent  = '-৳' + disc.toFixed(2) + ' (' + comm + '%)';
        document.getElementById('ppFinal').textContent = '৳' + final.toFixed(2);
        document.getElementById('pricePreview').style.display = 'block';
    } else {
        document.getElementById('pricePreview').style.display = 'none';
    }
}

function openAdd() {
    document.getElementById('modalTitle').innerHTML = '<i class="fas fa-plus-circle" style="color:var(--primary)"></i> Add Drive Package';
    document.getElementById('formAction').value = 'add';
    document.getElementById('formId').value = '';
    ['fName','fData','fVoice','fSms','fValidity','fDesc'].forEach(id => document.getElementById(id).value = '');
    document.getElementById('fApiPrice').value = '';
    document.getElementById('fComm').value = '';
    document.getElementById('fPrice').value = '';
    document.getElementById('fOp').value = '';
    document.getElementById('fCashback').value = '0';
    document.getElementById('fType').value = 'data';
    document.getElementById('fStatus').value = 'active';
    document.getElementById('pricePreview').style.display = 'none';
    document.getElementById('pkgModal').classList.add('show');
}

function openEdit(p) {
    document.getElementById('modalTitle').innerHTML = '<i class="fas fa-edit" style="color:var(--primary)"></i> Edit Package';
    document.getElementById('formAction').value = 'edit';
    document.getElementById('formId').value      = p.id;
    document.getElementById('fName').value       = p.name;
    document.getElementById('fOp').value         = p.operator_id || '';
    document.getElementById('fType').value       = p.type || 'data';
    document.getElementById('fData').value       = p.data_amount || '';
    document.getElementById('fVoice').value      = p.voice_minutes || '';
    document.getElementById('fSms').value        = p.sms_count || '';
    document.getElementById('fValidity').value   = p.validity || '';
    document.getElementById('fApiPrice').value   = p.api_price || '';
    document.getElementById('fComm').value       = p.commission_percent || '';
    document.getElementById('fPrice').value      = p.price || '';
    document.getElementById('fDesc').value       = p.description || '';
    document.getElementById('fStatus').value     = p.status || 'active';
    document.getElementById('fCashback').value   = p.cashback_amount || '0';
    calcPrice();
    document.getElementById('pkgModal').classList.add('show');
}

function closeModal() { document.getElementById('pkgModal').classList.remove('show'); }

function toggleAll(cb) {
    document.querySelectorAll('.row-cb').forEach(c => c.checked = cb.checked);
    updateSelCount();
}

function updateSelCount() {
    const cnt = document.querySelectorAll('.row-cb:checked').length;
    const el = document.getElementById('selCount');
    if(el) el.textContent = cnt > 0 ? cnt+' selected' : '';
    const selAll = document.getElementById('selAll');
    const total = document.querySelectorAll('.row-cb').length;
    if(selAll) selAll.checked = cnt === total && total > 0;
}

function setEcareMode(mode) {
    document.getElementById('autoSyncEnabled').value = mode === 'autosync' ? '1' : '0';
}

function setPkgSource(source) {
    const apiMap   = {ecare_direct:'ecare', ecare_sync:'ecare', st_sync:'successtopup'};
    const enableMap= {ecare_direct:'0',     ecare_sync:'1',     st_sync:'1'};
    document.getElementById('autoSyncApi').value    = apiMap[source]    || 'ecare';
    document.getElementById('autoSyncEnabled').value= enableMap[source] || '0';
    document.getElementById('syncNowApi').value     = apiMap[source]    || 'ecare';
}

function applyBulk() {
    const action = document.getElementById('bulkAction').value;
    if (!action) { alert('Please select a bulk action'); return; }
    const checked = document.querySelectorAll('.row-cb:checked');
    if (!checked.length) { alert('Please select at least one package'); return; }
    const label = {active:'Activate', inactive:'Deactivate', delete:'DELETE'}[action];
    if (!confirm(label + ' ' + checked.length + ' package(s)?')) return;

    // Build hidden inputs dynamically
    const hiddenDiv = document.getElementById('hiddenIds');
    hiddenDiv.innerHTML = '';
    checked.forEach(cb => {
        const inp = document.createElement('input');
        inp.type = 'hidden';
        inp.name = 'bulk_ids[]';
        inp.value = cb.dataset.id;
        hiddenDiv.appendChild(inp);
    });

    document.getElementById('bulkActionVal').value = action;
    document.getElementById('bulkForm').submit();
}

function updateSyncHint() {
    const api = document.getElementById('syncApiSel').value;
    const hint = document.getElementById('syncHint');
    if (api === 'ecare') {
        hint.style.background = '#fffaf0';
        hint.style.color = '#744210';
        hint.textContent = '⚡ ECARE Technology থেকে offer packages import হবে। Operator select করুন।';
    } else {
        hint.style.background = '#f0fff4';
        hint.style.color = '#276749';
        hint.textContent = '🔄 SuccessTopUp থেকে packages import হবে। API commission → cashback হিসেবে add হবে।';
    }
}
</script>
</body>
</html>
