<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once 'includes/config.php';
// Commission applied inline after success
require_once 'includes/successtopup.php';
require_once 'includes/telegram.php';
requireLogin();
require_once 'includes/service_check.php';
checkServiceEnabled('drive');
$user = getCurrentUser();
$db   = getDB();

// Auto-create drive_requests table if missing
try {
    $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
    )");
} catch(Exception $e) {}

// User preferred currency
$_drv_uc = null;
try {
    $s = $db->prepare("SELECT c.* FROM users u JOIN currencies c ON u.preferred_currency=c.code WHERE u.id=? AND c.is_active=1 AND c.code<>'BDT'");
    $s->execute([$user['id']]);
    $_drv_uc = $s->fetch() ?: null;
} catch(Exception $e) {}

// User's drive commission rate from package
$driveCommRate = 0;
try {
    $r = $db->prepare("SELECT p.drive_commission FROM users u LEFT JOIN user_packages p ON COALESCE(u.package_id,1)=p.id WHERE u.id=?");
    $r->execute([$user['id']]);
    $driveCommRate = floatval($r->fetchColumn() ?: 0);
} catch(Exception $e) {}

$error = ''; $success = '';
if (isset($_GET['success'])) $success = sanitize($_GET['success']);

// Handle purchase
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $pkgApiId = sanitize($_POST['package_api_id'] ?? '');
    $pkgId    = intval($_POST['package_id'] ?? 0);
    $phone    = preg_replace('/[^0-9+]/', '', $_POST['phone'] ?? '');
    $drive_auto_api = getSetting('drive_auto_sync_api') ?: 'ecare';

    if (!$pkgApiId && !$pkgId) { $error = 'Please select a package!'; }
    elseif (strlen($phone) < 10) { $error = 'Please enter valid phone number!'; }
    else {
        $pkg = null;

        // ECARE real-time mode — package data comes from POST (not DB)
        if ($drive_auto_api === 'ecare' && $pkgApiId && strpos($pkgApiId,'ECARE_') === 0) {
            $pkg = [
                'id'              => null,
                'name'            => sanitize($_POST['pkg_name'] ?? 'Drive Package'),
                'price'           => floatval($_POST['pkg_price'] ?? 0),
                'api_package_id'  => $pkgApiId,
                'operator_id'     => intval($_POST['pkg_op_id'] ?? 0),
                'op_name'         => sanitize($_POST['pkg_op_name'] ?? ''),
                'op_code'         => sanitize($_POST['pkg_op_code'] ?? ''),
                'commission_percent' => 0,
                'cashback_amount' => floatval($_POST['pkg_cashback'] ?? 0),
                'data_amount'     => '',
                'voice_minutes'   => '',
            ];
            if (!$pkg['price']) $pkg = null;
        } else {
            // DB mode
            $stmt = $db->prepare("SELECT dp.*, o.name as op_name, o.code as op_code FROM drive_packages dp LEFT JOIN operators o ON dp.operator_id=o.id WHERE dp.id=? AND dp.status='active'");
            $stmt->execute([$pkgId]);
            $pkg = $stmt->fetch() ?: null;
        }

        if (!$pkg) { $error = 'Package not found!'; }
        elseif ($user['balance'] < $pkg['price']) {
            $error = 'Insufficient balance! Need: '.CURRENCY.number_format($pkg['price'],2).' | Have: '.CURRENCY.number_format($user['balance'],2);
        } else {
            $ref = 'DRV'.strtoupper(substr(uniqid(),7));
            $balBefore = $user['balance'];
            $balAfter  = $balBefore - $pkg['price'];

            try {
                $db->beginTransaction();
                $db->prepare("UPDATE users SET balance=balance-? WHERE id=?")->execute([$pkg['price'],$user['id']]);

                $commAmt     = ($pkg['price'] * floatval($pkg['commission_percent'])) / 100;
                $driveStatus = 'pending';
                $driveNote   = 'Awaiting admin approval';
                $apiPkgId    = $pkg['api_package_id'] ?? null;
                $apiRespJson = null;
                $isEcare     = $apiPkgId && strpos($apiPkgId, 'ECARE_') === 0;
                $drive_mode  = getSetting('drive_mode') ?: 'manual';

                // Auto mode
                if ($drive_mode === 'auto') {
                    if ($isEcare) {
                        // ECARE direct call
                        require_once 'includes/ecare.php';
                        $ecareOpCode = $pkg['op_code'] ?? '';
                        // Extract from api_package_id: ECARE_GP_xxxx → GP
                        if (empty($ecareOpCode) && $apiPkgId) {
                            $parts = explode('_', $apiPkgId);
                            $ecareOpCode = $parts[1] ?? '';
                        }
                        if ($ecareOpCode) {
                            $ecareRef    = $ref . substr(microtime(true)*1000,-4);
                            $ecareResp   = ecareRecharge($phone, $pkg['price'], $ecareOpCode, 'prepaid', $ecareRef);
                            $apiRespJson = json_encode(['ecare_ref'=>$ecareRef,'rc_status'=>$ecareResp['rc_status'],'trxid'=>$ecareResp['trxid'],'raw'=>$ecareResp['raw']], JSON_UNESCAPED_UNICODE);

                            if ($ecareResp['received']) {
                                // RECEIVED = sent to network, wait for cron status check
                                $driveStatus = 'pending';
                                $driveNote   = '⏳ ECARE RECEIVED — status check pending';
                            } elseif ($ecareResp['result']) {
                                // Immediate SUCCESS (rare)
                                $driveStatus = 'success';
                                $driveNote   = '✅ ECARE SUCCESS TrxID:'.($ecareResp['trxid']??'');
                            } else {
                                $driveStatus = 'pending';
                                $driveNote   = '❌ ECARE '.($ecareResp['rc_status']??'FAILED').': '.($ecareResp['message']??'').' | Admin pending';
                            }
                        } else {
                            $driveNote = '⏳ ECARE pending — operator code missing';
                        }
                    } elseif ($apiPkgId) {
                        // SuccessTopUp
                        require_once 'includes/successtopup.php';
                        $stOpCode = '';
                        try {
                            $opRow = $db->prepare("SELECT code FROM operators WHERE id=?");
                            $opRow->execute([$pkg['operator_id']]);
                            $stOpCode = $opRow->fetchColumn() ?: '';
                        } catch(Exception $e) {}
                        $apiResp     = successTopupDrive($phone, $apiPkgId, $stOpCode, $ref);
                        $apiRespJson = json_encode($apiResp, JSON_UNESCAPED_UNICODE);
                        if (isset($apiResp['result']) && $apiResp['result'] === true) {
                            $driveStatus = 'success';
                            $driveNote   = '✅ SuccessTopUp Drive sent';
                        } else {
                            $driveNote = 'ST Failed: '.($apiResp['message']??'Unknown').' | Pending admin';
                        }
                    }
                }

                // For ECARE real-time — save package name and op in note
                $driveNote = $driveNote . ' | PKG:'.($pkg['name']??'') . ' | OP:'.($pkg['op_code']??'') . ' | OP_NAME:'.($pkg['op_name']??'');

                $db->prepare("INSERT INTO drive_requests (user_id,package_id,phone_number,amount,commission_percent,commission_amount,balance_before,balance_after,reference,status,note,api_response) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)")
                   ->execute([$user['id'], $pkg['id'] ?: null, $phone, $pkg['price'], $pkg['commission_percent'], $commAmt, $balBefore, $balAfter, $ref, $driveStatus, $driveNote, $apiRespJson]);

                $txnStatus = $driveStatus === 'success' ? 'success' : 'pending';
                $db->prepare("INSERT INTO transactions (user_id,type,amount,charge,net_amount,balance_before,balance_after,reference,status,note) VALUES (?,?,?,0,?,?,?,?,?,?)")
                   ->execute([$user['id'],'drive',$pkg['price'],$pkg['price'],$balBefore,$balAfter,$ref,$txnStatus,
                              'Drive: '.$pkg['name'].' | '.$phone]);

                $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'info')")
                   ->execute([$user['id'],'⚡ Drive Request Sent!','Package: '.$pkg['name'].' for '.$phone.'. Ref: '.$ref]);

                // Telegram notification
                $modeLabel   = $isEcare ? '⚡ ECARE' : ($drive_mode === 'auto' ? '⚡ Auto' : '🖐 Manual');
                $statusLabel = $driveStatus === 'success' ? '✅ Success' : '⏳ Pending';

                $tgData = [
                    '👤 User'     => $user['name'],
                    '📱 Phone'   => $phone,
                    '📦 Package' => $pkg['name'],
                    '📡 Operator'=> $pkg['op_name']??'-',
                    '💰 Amount'  => CURRENCY.number_format($pkg['price'],2),
                    '🔖 Ref'     => $ref,
                    '🕐 Time'    => date('d M Y, h:i A'),
                    '⚙️ API'     => $modeLabel,
                    '📊 Status'  => $statusLabel,
                ];
                notifyPending('drive', $user['name'], $tgData);

                $db->commit();
                // Commission on success only — base = cashback_amount from API
                if ($driveStatus === 'success') {
                    try {
                        $cashbackBase = floatval($pkg['cashback_amount'] ?? 0);
                        // applyCommission with cashback_amount as base
                        applyCommission($db, $user['id'], 'drive', $pkg['price'], $ref, $cashbackBase);
                    } catch(Exception $ce) {}
                } // end if success
                $success = $driveStatus === "success" ? "✅ Drive successful! Ref: $ref" : "⏳ Drive request submitted! Ref: $ref";
                header('Location: drive.php?success='.urlencode($success)); exit;
                $user = getCurrentUser(); // refresh balance
            } catch(Exception $e) {
                $db->rollBack();
                $error = 'Error: '.$e->getMessage();
            }
        }
    }
}

// Drive mode setting
$drive_auto_api = getSetting('drive_auto_sync_api') ?: 'ecare';
require_once 'includes/ecare.php';

$packages = [];
$apiError  = '';

// Operator name mapping — ECARE response keys
$opNames = [
    'GP' => 'Grameenphone',
    'BL' => 'Banglalink',
    'RB' => 'Robi',
    'AR' => 'Airtel',
];

if ($drive_auto_api === 'ecare') {
    // Single ECARE API call — returns all operators in one response
    $access_id   = getSetting('ecare_username') ?: '';
    $access_pass = getSetting('ecare_password') ?: '';

    if (!$access_id || !$access_pass) {
        $apiError = 'ECARE credentials not configured.';
    } else {
        try {
            $url = 'http://118.179.129.98/myportal/api/rechargeapi/recharge_api_thirdparty.php?' . http_build_query([
                'access_id'   => $access_id,
                'access_pass' => $access_pass,
                'service'     => 'OFFERPACK',
            ]);
            $ch = curl_init($url);
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT        => 15,
                CURLOPT_CONNECTTIMEOUT => 10,
                CURLOPT_SSL_VERIFYPEER => false,
            ]);
            $res = curl_exec($ch);
            curl_close($ch);

            $data = $res ? json_decode($res, true) : null;

            if ($data && ($data['STATUS']??'') === 'OK') {
                // Parse each operator key: GP, BL, RB
                foreach ($opNames as $opCode => $opNameStr) {
                    $items = $data[$opCode] ?? [];
                    if (empty($items)) continue;

                    // Get operator DB id (AR in ECARE = AL in DB)
                    $dbCode = ($opCode === 'AR') ? 'AL' : $opCode;
                    $opRow = $db->prepare("SELECT id FROM operators WHERE UPPER(code)=? AND status='active' LIMIT 1");
                    $opRow->execute([strtoupper($dbCode)]);
                    $opDbId = $opRow->fetchColumn() ?: null;

                    foreach ($items as $ap) {
                        if (!is_array($ap) || ($ap['_status']??'') !== 'A') continue;
                        $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']??'';
                        if (!$apPrice) continue;

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

                        $nameParts = [];
                        if ($hasData)  $nameParts[] = $apData;
                        if ($hasVoice) $nameParts[] = $apVoice . ' Min';
                        $apName = empty($nameParts) ? '৳'.$apPrice.' Pack' : implode(' + ',$nameParts).' ('.$apValid.')';
                        $apiId  = 'ECARE_'.$opCode.'_'.md5($apName.$apPrice);

                        $packages[] = [
                            'id'               => $apiId,
                            'name'             => $apName,
                            'op_name'          => $opNameStr,
                            'op_code'          => $opCode,
                            'operator_id'      => $opDbId,
                            'type'             => $apType,
                            'data_amount'      => $hasData  ? $apData  : '',
                            'voice_minutes'    => $hasVoice ? $apVoice : '',
                            'sms_count'        => '',
                            'validity'         => $apValid,
                            'price'            => $apPrice,
                            'api_price'        => $apPrice,
                            'cashback_amount'  => $apComm,
                            'api_package_id'   => $apiId,
                            'status'           => 'active',
                            'commission_percent' => 0,
                        ];
                    }
                }
            } else {
                $apiError = 'ECARE API unavailable. Try again later.';
            }
        } catch(Exception $e) {
            $apiError = 'Connection error. Try again later.';
        }
    }

    if (empty($packages) && !$apiError) {
        $apiError = 'No drive packages available at this time.';
    }

} else {
    // SuccessTopUp sync mode OR ECARE auto sync — from DB
    $packages = $db->query("SELECT dp.*, o.name as op_name, o.code as op_code FROM drive_packages dp LEFT JOIN operators o ON dp.operator_id=o.id WHERE dp.status='active' ORDER BY dp.operator_id, dp.type, dp.price")->fetchAll();
    if (empty($packages)) $apiError = 'No packages available. Please sync from API first.';
}

// Group by operator
$grouped = [];
foreach ($packages as $p) {
    $key = $p['op_name'] ?? 'Other';
    $grouped[$key][] = $p;
}

// Recent requests
$recentReqs = $db->prepare("SELECT dr.*, dp.name as pkg_name FROM drive_requests dr LEFT JOIN drive_packages dp ON dr.package_id=dp.id WHERE dr.user_id=? ORDER BY dr.created_at DESC LIMIT 5");
$recentReqs->execute([$user['id']]);
$requests = $recentReqs->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>Drive - <?= SITE_NAME ?></title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<style>
*{margin:0;padding:0;box-sizing:border-box;-webkit-tap-highlight-color:transparent}
:root{
            --primary:<?= getSetting('color_primary') ?: '#1a3c8f' ?>;
            --secondary:<?= getSetting('color_secondary') ?: '#f5a623' ?>;
            --dark:<?= getSetting('color_dark') ?: '#0d1f4e' ?>;
        }
body{font-family:'Segoe UI',sans-serif;background:#f5f7fa;padding-bottom:90px}

.hdr{background:linear-gradient(135deg,var(--dark),var(--primary));padding:0 18px;position:sticky;top:0;z-index:50}
.hdr-in{display:flex;align-items:center;gap:12px;height:58px;max-width:480px;margin:0 auto}
.back-btn{width:36px;height:36px;background:rgba(255,255,255,0.15);border:none;color:white;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:17px;cursor:pointer;flex-shrink:0}
.hdr-title{color:white;font-size:18px;font-weight:700;flex:1}
.hdr-bal{background:rgba(255,255,255,0.15);color:white;padding:6px 12px;border-radius:10px;font-size:13px;font-weight:700}

.hero{background:linear-gradient(135deg,var(--dark),var(--primary));padding:0 18px 18px}
.hero-in{max-width:480px;margin:0 auto}
.bal-card{background:rgba(255,255,255,0.12);border-radius:14px;padding:14px 16px;display:flex;align-items:center;justify-content:space-between}
.bal-left .lbl{color:rgba(255,255,255,0.65);font-size:11px;font-weight:600;margin-bottom:3px}
.bal-left .amt{color:white;font-size:22px;font-weight:800}
.bal-left .dual{color:rgba(255,255,255,0.55);font-size:11px;margin-top:2px}

.content{max-width:480px;margin:0 auto;padding:16px 16px}

.alert{padding:12px 15px;border-radius:12px;margin-bottom:14px;font-size:13px;font-weight:600;display:flex;align-items:center;gap:8px}
.alert-ok{background:#f0fff4;color:#276749;border:1px solid #c6f6d5}
.alert-err{background:#fff5f5;color:#c53030;border:1px solid #fed7d7}

/* Operator tabs */
.op-tabs{display:flex;gap:8px;overflow-x:auto;padding-bottom:4px;margin-bottom:14px;scrollbar-width:none}
.op-tabs::-webkit-scrollbar{display:none}
.op-tab{padding:8px 16px;border:2px solid #e8ecf4;border-radius:20px;background:white;font-size:13px;font-weight:700;cursor:pointer;white-space:nowrap;color:#666;flex-shrink:0;transition:0.2s}
.op-tab.active{border-color:var(--primary);background:var(--primary);color:white}

/* Type filter */
.type-tabs{display:flex;gap:6px;margin-bottom:14px}
.type-tab{flex:1;padding:8px;border:2px solid #e8ecf4;border-radius:10px;background:white;font-size:12px;font-weight:700;cursor:pointer;text-align:center;color:#666;transition:0.2s}
.type-tab.active{border-color:var(--primary);background:#eef2ff;color:var(--primary)}

/* Search */
.search-wrap{position:relative;margin-bottom:12px}
.search-wrap i{position:absolute;left:13px;top:50%;transform:translateY(-50%);color:#aaa;font-size:14px}
.search-in{width:100%;padding:12px 12px 12px 38px;border:2px solid #e8ecf4;border-radius:12px;font-size:14px;outline:none;background:white}
.search-in:focus{border-color:var(--primary)}

/* Package cards — SuccessTopUp style */
.pkg-card{background:white;border-radius:14px;padding:14px 16px;margin-bottom:8px;box-shadow:0 1px 6px rgba(0,0,0,0.07);cursor:pointer;border:2px solid #f0f0f0;transition:0.15s;position:relative;display:flex;align-items:flex-start;gap:12px}
.pkg-card:active{transform:scale(0.97)}
.pkg-card.selected{border-color:var(--primary);background:#f7f9ff;box-shadow:0 3px 14px rgba(26,60,143,0.12)}
.pkg-op-icon{width:42px;height:42px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:20px;flex-shrink:0;margin-top:2px}
.pkg-body{flex:1;min-width:0}
.pkg-name{font-size:14px;font-weight:700;color:#1a1a1a;line-height:1.4;margin-bottom:5px}
.pkg-price-row{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:4px}
.pkg-price{font-size:16px;font-weight:800;color:#e53e3e}
.pkg-dual{font-size:11px;color:#aaa;font-weight:500}
.pkg-right-col{text-align:right;font-size:12px;color:#888;flex-shrink:0}
.pkg-validity-txt{font-weight:600;color:#555}
.pkg-cashback-txt{color:#38a169;font-weight:700;margin-top:2px}
.pkg-selected-check{position:absolute;top:12px;right:12px;width:22px;height:22px;background:var(--primary);border-radius:50%;display:none;align-items:center;justify-content:center;color:white;font-size:12px;font-weight:800}
.pkg-card.selected .pkg-selected-check{display:flex}

/* Phone input */
.phone-section{background:white;border-radius:16px;padding:16px;margin-bottom:14px;box-shadow:0 2px 8px rgba(0,0,0,0.06);display:none}
.phone-section.show{display:block}
.phone-label{font-size:12px;font-weight:700;color:#555;text-transform:uppercase;letter-spacing:0.4px;margin-bottom:8px}
.phone-input-wrap{display:flex;gap:8px}
.phone-in{flex:1;padding:12px 14px;border:2px solid #e8ecf4;border-radius:12px;font-size:16px;font-weight:700;outline:none;transition:0.2s}
.phone-in:focus{border-color:var(--primary)}

/* Submit */
.submit-btn{width:100%;padding:15px;background:linear-gradient(135deg,var(--primary),#2856c8);color:white;border:none;border-radius:14px;font-size:15px;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px;transition:0.2s}
.submit-btn:disabled{background:#c8d0db;cursor:not-allowed}

/* History */
.hist-card{background:white;border-radius:12px;padding:13px;margin-bottom:8px;box-shadow:0 2px 6px rgba(0,0,0,0.04);display:flex;align-items:center;gap:12px}
.hist-ic{width:40px;height:40px;background:#eef2ff;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:18px;flex-shrink:0}
.hist-info{flex:1}
.hist-name{font-size:13px;font-weight:700;color:#333}
.hist-sub{font-size:11px;color:#aaa;margin-top:2px}
.hist-right{text-align:right}
.hist-amt{font-size:14px;font-weight:800;color:#e53e3e}
.hist-status{font-size:11px;font-weight:700;padding:3px 9px;border-radius:20px;margin-top:3px;display:inline-block}
.s-pending{background:#fffaf0;color:#d69e2e}
.s-success{background:#f0fff4;color:#38a169}
.s-failed{background:#fff5f5;color:#e53e3e}

.empty{text-align:center;padding:40px;color:#aaa}
.sec-title{font-size:14px;font-weight:700;color:var(--dark);margin-bottom:12px;display:flex;align-items:center;gap:8px}
</style>
</head>
<body>

<div class="hdr">
    <div class="hdr-in">
        <button class="back-btn" onclick="history.back()"><i class="fas fa-arrow-left"></i></button>
        <div class="hdr-title">⚡ Drive</div>
        <div class="hdr-bal"><?= CURRENCY ?><?= number_format($user['balance'],0) ?></div>
    </div>
</div>

<div class="hero">
    <div class="hero-in">
        <div class="bal-card">
            <div class="bal-left">
                <div class="lbl">AVAILABLE BALANCE</div>
                <div class="amt"><?= CURRENCY ?><?= number_format($user['balance'],2) ?></div>
                <?php if($_drv_uc): ?>
                <div class="dual">≈ <?= htmlspecialchars($_drv_uc['symbol']) ?><?= number_format($user['balance']*floatval($_drv_uc['rate']),2) ?> <?= $_drv_uc['code'] ?></div>
                <?php endif; ?>
            </div>
            <div style="font-size:28px">⚡</div>
        </div>
    </div>
</div>

<div class="content">
    <?php if($error): ?><div class="alert alert-err"><i class="fas fa-times-circle"></i> <?= htmlspecialchars($error) ?></div><?php endif; ?>
    <?php if($success): ?><div class="alert alert-ok"><i class="fas fa-check-circle"></i> <?= htmlspecialchars($success) ?></div><?php endif; ?>

    <?php if($apiError || empty($packages)): ?>
    <div style="text-align:center;padding:40px;background:white;border-radius:14px">
        <div style="font-size:40px;margin-bottom:12px">📭</div>
        <div style="font-size:16px;font-weight:700;color:#333;margin-bottom:6px">No Drive Packages Available</div>
        <div style="font-size:13px;color:#aaa">এই মুহূর্তে কোনো drive package নেই।<br>কিছুক্ষণ পর আবার চেষ্টা করুন।</div>
    </div>
    <?php else: ?>

    <!-- Search -->
    <div class="search-wrap">
        <i class="fas fa-search"></i>
        <input type="text" class="search-in" id="pkgSearch" placeholder="Search packages... e.g. 10GB, 500MIN, Combo"
            oninput="searchPkgs(this.value)">
    </div>

    <!-- Operator Tabs -->
    <div class="op-tabs" id="opTabs">
        <div class="op-tab active" onclick="filterOp('all',this)">All</div>
        <?php foreach(array_keys($grouped) as $opName): ?>
        <div class="op-tab" onclick="filterOp('<?= htmlspecialchars($opName,ENT_QUOTES) ?>',this)"><?= htmlspecialchars($opName) ?></div>
        <?php endforeach; ?>
    </div>

    <!-- Type Filter -->
    <div class="type-tabs">
        <div class="type-tab active" onclick="filterType('all',this)">🔀 All</div>
        <div class="type-tab" onclick="filterType('data',this)">📶 Data</div>
        <div class="type-tab" onclick="filterType('voice',this)">📞 Voice</div>
        <div class="type-tab" onclick="filterType('combo',this)">⚡ Combo</div>
    </div>

    <!-- Packages -->
    <form method="POST" id="driveForm">
        <input type="hidden" name="package_id" id="selectedPkg" value="0">
        <input type="hidden" name="package_api_id" id="selectedPkgApiId">
        <input type="hidden" name="pkg_name" id="selectedPkgName">
        <input type="hidden" name="pkg_price" id="selectedPkgPrice">
        <input type="hidden" name="pkg_op_id" id="selectedPkgOpId">
        <input type="hidden" name="pkg_op_name" id="selectedPkgOpName">
        <input type="hidden" name="pkg_op_code" id="selectedPkgOpCode">
        <input type="hidden" name="pkg_cashback" id="selectedPkgCashback">
        <div id="pkgList">
        <?php foreach($packages as $p):
            $typeIcons = ['data'=>'📶','voice'=>'📞','combo'=>'⚡','sms'=>'💬'];
            $icon = $typeIcons[$p['type']]??'📦';
            $opName = strtoupper($p['op_name']??'');
            $opColor = '#1a3c8f';
            if(strpos($opName,'GRAMEEN')!==false||strpos($opName,'GP')!==false) $opColor='#009B3A';
            elseif(strpos($opName,'BANGLA')!==false||strpos($opName,'BL')!==false) $opColor='#FF6B00';
            elseif(strpos($opName,'ROBI')!==false) $opColor='#E4001D';
            elseif(strpos($opName,'TELETALK')!==false) $opColor='#1C3F7A';
            elseif(strpos($opName,'AIRTEL')!==false) $opColor='#F7941D';
            $opInitials = strtoupper(substr($p['op_name']??'?',0,2));
        ?>
        <div class="pkg-card"
            data-op="<?= htmlspecialchars($p['op_name']??'Other',ENT_QUOTES) ?>"
            data-type="<?= $p['type'] ?>"
            data-name="<?= htmlspecialchars(strtolower($p['name']),ENT_QUOTES) ?>"
            data-id="<?= $p['id'] ?>"
            data-api-id="<?= htmlspecialchars($p['api_package_id']??'',ENT_QUOTES) ?>"
            data-price="<?= $p['price'] ?>"
            data-op-id="<?= $p['operator_id'] ?>"
            data-op-name="<?= htmlspecialchars($p['op_name']??'',ENT_QUOTES) ?>"
            data-op-code="<?= htmlspecialchars($p['op_code']??'',ENT_QUOTES) ?>"
            data-cashback="<?= $p['cashback_amount'] ?>">

            <!-- Operator Icon -->
            <div class="pkg-op-icon" style="background:<?= $opColor ?>18;border:2px solid <?= $opColor ?>44">
                <span style="font-size:11px;font-weight:900;color:<?= $opColor ?>"><?= $opInitials ?></span>
            </div>

            <!-- Content -->
            <div class="pkg-body">
                <!-- Name + price row -->
                <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:8px;margin-bottom:6px">
                    <div style="flex:1">
                        <div class="pkg-name"><?= htmlspecialchars($p['name']) ?></div>
                        <?php if($p['op_name']): ?><div style="font-size:11px;color:#aaa;margin-top:1px"><?= htmlspecialchars($p['op_name']) ?></div><?php endif; ?>
                    </div>
                    <div style="text-align:right;flex-shrink:0">
                        <div class="pkg-price"><?= CURRENCY ?><?= number_format($p['price'],2) ?></div>
                        <?php if($_drv_uc): ?>
                        <div class="pkg-dual">≈ <?= htmlspecialchars($_drv_uc['symbol']) ?><?= number_format($p['price']*floatval($_drv_uc['rate']),2) ?> <?= $_drv_uc['code'] ?></div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Cashback / Commission -->
                <?php
                $pkgCashback = floatval($p['cashback_amount']??0);
                if($pkgCashback > 0):
                    // User's actual commission = cashback × drive_commission%
                    $actualComm = ($driveCommRate > 0) ? round($pkgCashback * $driveCommRate / 100, 2) : $pkgCashback;
                ?>
                <div style="background:#f0fff4;border:1px solid #c6f6d5;border-radius:20px;padding:4px 12px;margin-bottom:7px;font-size:12px;font-weight:700;color:#276749;display:inline-flex;align-items:center;gap:5px">
                    💰 +<?= CURRENCY ?><?= number_format($actualComm, 2) ?> Commission
                    <?php if($_drv_uc && floatval($_drv_uc['rate'])>0): ?>
                    <span style="color:#aaa;font-weight:500;font-size:11px">≈ <?= htmlspecialchars($_drv_uc['symbol']) ?><?= number_format($actualComm*floatval($_drv_uc['rate']),2) ?> <?= $_drv_uc['code'] ?></span>
                    <?php endif; ?>
                </div>
                <?php endif; ?>

                <!-- Tags row -->
                <div style="display:flex;gap:6px;flex-wrap:wrap;align-items:center">
                    <?php if($p['data_amount']): ?>
                    <span style="font-size:12px;color:#555;font-weight:600">📶 <?= htmlspecialchars($p['data_amount']) ?></span>
                    <?php endif; ?>
                    <?php if($p['voice_minutes']): ?>
                    <span style="font-size:12px;color:#555;font-weight:600">📞 <?= htmlspecialchars($p['voice_minutes']) ?></span>
                    <?php endif; ?>
                    <?php if($p['validity']): ?>
                    <span style="font-size:12px;color:#888">⏱ <?= htmlspecialchars($p['validity']) ?></span>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Selected check -->
            <div class="pkg-selected-check">✓</div>
        </div>
        <?php endforeach; ?>
        </div>

        <!-- Phone Input -->
        <div class="phone-section" id="phoneSection">
            <!-- Selected Package Summary -->
            <div id="pkgSummary" style="background:linear-gradient(135deg,var(--dark),var(--primary));border-radius:14px;padding:14px 16px;margin-bottom:14px;color:white">
                <div style="font-size:10px;opacity:0.7;font-weight:600;letter-spacing:1px;margin-bottom:6px">SELECTED PACKAGE</div>
                <div style="font-size:15px;font-weight:800" id="sumName">—</div>
                <div style="display:flex;align-items:center;justify-content:space-between;margin-top:8px">
                    <div>
                        <div style="font-size:22px;font-weight:900;color:#ffd54f" id="sumPrice">—</div>
                        <div style="font-size:11px;opacity:0.65" id="sumDual"></div>
                    </div>
                    <div id="sumCashback" style="display:none;background:rgba(255,255,255,0.15);border-radius:12px;padding:8px 12px;text-align:center">
                        <div style="font-size:10px;opacity:0.75;font-weight:600">CASHBACK</div>
                        <div style="font-size:16px;font-weight:800;color:#69f0ae" id="sumCbAmt"></div>
                        <div style="font-size:10px;opacity:0.65" id="sumCbDual"></div>
                    </div>
                </div>
            </div>

            <!-- Phone input -->
            <div style="font-size:12px;font-weight:700;color:#555;text-transform:uppercase;letter-spacing:0.5px;margin-bottom:8px">📱 Enter Phone Number</div>
            <div style="position:relative;margin-bottom:10px">
                <span style="position:absolute;left:14px;top:50%;transform:translateY(-50%);font-size:14px;color:#aaa">🇧🇩</span>
                <input type="tel" name="phone" id="phoneIn" placeholder="01XXXXXXXXX" maxlength="15" oninput="checkReady()"
                    style="width:100%;padding:14px 14px 14px 42px;border:2px solid #e8ecf4;border-radius:12px;font-size:18px;font-weight:700;outline:none;transition:0.2s;color:var(--primary)"
                    onfocus="this.style.borderColor='var(--primary)'" onblur="this.style.borderColor='#e8ecf4'">
            </div>
            <div style="font-size:11px;color:#aaa;margin-bottom:4px">📌 Make sure the number matches the operator</div>
        </div>

        <button type="submit" class="submit-btn" id="submitBtn" disabled>
            <i class="fas fa-bolt"></i> Submit Drive Request
        </button>
    </form>
    <?php endif; ?>

    <!-- Recent Requests -->
    <?php if(!empty($requests)): ?>
    <div style="margin-top:20px">
        <div class="sec-title"><i class="fas fa-history" style="color:#805ad5"></i> Recent Requests</div>
        <?php foreach($requests as $r): ?>
        <div class="hist-card">
            <div class="hist-ic">⚡</div>
            <div class="hist-info">
                <div class="hist-name"><?= htmlspecialchars($r['pkg_name']??'-') ?></div>
                <div class="hist-sub"><?= $r['phone_number'] ?> • <?= date('d M, h:i A',strtotime($r['created_at'])) ?></div>
            </div>
            <div class="hist-right">
                <div class="hist-amt">-<?= CURRENCY ?><?= number_format($r['amount'],2) ?></div>
                <span class="hist-status s-<?= $r['status'] ?>"><?= ucfirst($r['status']) ?></span>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>

<?php include 'includes/bottom_nav.php'; ?>

<script>
const UC_RATE = <?= $_drv_uc ? floatval($_drv_uc['rate']) : 0 ?>;
const UC_SYM  = "<?= $_drv_uc ? addslashes(htmlspecialchars($_drv_uc['symbol'])) : '' ?>";
const UC_CODE = "<?= $_drv_uc ? $_drv_uc['code'] : '' ?>";
const PKG_CASHBACK = {<?php foreach($packages as $p): ?><?= $p['id'] ?>:<?= floatval($p['cashback_amount']??0) ?>,<?php endforeach; ?>};

let selPkgId = 0;
let curOp    = 'all';
let curType  = 'all';

function filterOp(op, el) {
    curOp = op;
    document.querySelectorAll('.op-tab').forEach(t => t.classList.remove('active'));
    el.classList.add('active');
    filterPkgs();
}

function filterType(type, el) {
    curType = type;
    document.querySelectorAll('.type-tab').forEach(t => t.classList.remove('active'));
    el.classList.add('active');
    filterPkgs();
}

// Event delegation for pkg-card clicks
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.pkg-card').forEach(function(card) {
        card.addEventListener('click', function() {
            const id    = this.dataset.id;
            const price = parseFloat(this.dataset.price||0);
            const name  = this.dataset.op ? this.getAttribute('data-op')+' Package' : 'Package';
            // Get display name from pkg-name element
            const nameEl = this.querySelector('.pkg-name');
            const dispName = nameEl ? nameEl.textContent : name;
            selectPkg(id, price, dispName, this);
        });
    });
});

function filterPkgs() {
    const search = (document.getElementById('pkgSearch')?.value || '').toLowerCase();
    document.querySelectorAll('.pkg-card').forEach(c => {
        const opMatch     = curOp   === 'all' || c.dataset.op   === curOp;
        const typeMatch   = curType === 'all' || c.dataset.type === curType;
        const searchMatch = !search  || c.dataset.name?.includes(search) ||
                            c.textContent.toLowerCase().includes(search);
        c.style.display = (opMatch && typeMatch && searchMatch) ? 'block' : 'none';
    });
    selPkgId = 0;
    document.getElementById('selectedPkg').value = '';
    document.getElementById('phoneSection').classList.remove('show');
    checkReady();
}

function searchPkgs(val) { filterPkgs(); }

function selectPkg(id, price, name, el) {
    document.querySelectorAll('.pkg-card').forEach(c => c.classList.remove('selected'));
    el.classList.add('selected');
    selPkgId = id;

    // Set hidden fields
    document.getElementById('selectedPkg').value        = id || 0;
    document.getElementById('selectedPkgApiId').value   = el.dataset.apiId  || '';
    document.getElementById('selectedPkgName').value    = el.dataset.name   || name;
    document.getElementById('selectedPkgPrice').value   = el.dataset.price  || price;
    document.getElementById('selectedPkgOpId').value    = el.dataset.opId   || '';
    document.getElementById('selectedPkgOpName').value  = el.dataset.opName || '';
    document.getElementById('selectedPkgOpCode').value  = el.dataset.opCode || '';
    document.getElementById('selectedPkgCashback').value= el.dataset.cashback|| 0;

    // Summary card
    document.getElementById('sumName').textContent  = name;
    document.getElementById('sumPrice').textContent = '৳' + parseFloat(price).toFixed(2);
    document.getElementById('sumDual').textContent  = UC_RATE ? '≈ ' + UC_SYM + (price * UC_RATE).toFixed(2) + ' ' + UC_CODE : '';

    // Cashback
    const cb    = parseFloat(el.dataset.cashback || 0);
    const cbBox = document.getElementById('sumCashback');
    if (cb > 0) {
        document.getElementById('sumCbAmt').textContent  = '+৳' + cb.toFixed(0);
        document.getElementById('sumCbDual').textContent = UC_RATE ? '≈ ' + UC_SYM + (cb * UC_RATE).toFixed(2) + ' ' + UC_CODE : '';
        cbBox.style.display = 'block';
    } else {
        cbBox.style.display = 'none';
    }

    document.getElementById('phoneSection').classList.add('show');
    document.getElementById('phoneIn').focus();
    setTimeout(() => document.getElementById('phoneSection').scrollIntoView({behavior:'smooth',block:'nearest'}), 100);
    checkReady();
}

function checkReady() {
    const phone  = document.getElementById('phoneIn').value.replace(/\D/g,'');
    const btn    = document.getElementById('submitBtn');
    const apiId  = document.getElementById('selectedPkgApiId').value;
    const pkgId  = document.getElementById('selectedPkg').value;
    const hasPkg = (apiId && apiId.length > 0) || (pkgId && parseInt(pkgId) > 0);
    const ready  = hasPkg && phone.length >= 10;
    btn.disabled = !ready;
}
</script>
<script>document.addEventListener("DOMContentLoaded",function(){ if(window.pageReady) window.pageReady(); });</script>
</body>
</html>
