<?php
require_once 'includes/config.php';
require_once 'includes/telegram.php';
requireLogin();
require_once 'includes/service_check.php';
checkServiceEnabled('manual_drive');
$user = getCurrentUser();
$db   = getDB();

$error = ''; $success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_drive'])) {
    $catId  = intval($_POST['category_id'] ?? 0);
    $pkgId  = intval($_POST['package_id'] ?? 0);
    $opId   = intval($_POST['operator_id'] ?? 0);
    $title  = sanitize($_POST['title'] ?? '');
    $detail = sanitize($_POST['details'] ?? '');

    $pkg = null;
    if ($pkgId) {
        $stmt = $db->prepare("SELECT p.*, c.name as cat_name, c.icon as cat_icon, o.name as op_name, o.icon as op_icon FROM manual_drive_packages p JOIN manual_drive_categories c ON p.category_id=c.id JOIN manual_drive_operators o ON c.operator_id=o.id WHERE p.id=? AND p.is_active=1");
        $stmt->execute([$pkgId]); $pkg = $stmt->fetch();
    }
    $amount = $pkg ? floatval($pkg['price']) : 0;

    if (!$catId || !$title || !$detail) { $error = 'Please fill all required fields.'; }
    elseif ($amount > 0 && $user['balance'] < $amount) { $error = 'Insufficient balance! Required: ৳'.number_format($amount,2); }
    else {
        $ref = 'MDR'.strtoupper(substr(uniqid(),7));
        $balBefore = $user['balance']; $balAfter = $amount>0?$balBefore-$amount:$balBefore;
        $db->beginTransaction();
        try {
            if ($amount>0) $db->prepare("UPDATE users SET balance=balance-? WHERE id=?")->execute([$amount,$user['id']]);
            $db->prepare("INSERT INTO manual_drive_requests (user_id,operator_id,category_id,package_id,title,details,amount,reference,balance_before,balance_after,status) VALUES (?,?,?,?,?,?,?,?,?,?,'pending')")->execute([$user['id'],$opId,$catId,$pkgId?:null,$title,$detail,$amount,$ref,$balBefore,$balAfter]);
            // Save to transactions for history display
            if ($amount > 0) {
                $db->prepare("INSERT INTO transactions (user_id,type,amount,charge,net_amount,balance_before,balance_after,phone_number,reference,status,note) VALUES (?,?,?,0,?,?,?,?,?,?,?)")
                   ->execute([$user['id'],'manual_drive',$amount,$amount,$balBefore,$balAfter,$detail,$ref,'pending',$title]);
            }
            $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'info')")->execute([$user['id'],'📦 Drive Request Sent!',$title.' | Ref: '.$ref]);
            $ci = $db->prepare("SELECT c.*, o.name as op_name, o.icon as op_icon FROM manual_drive_categories c JOIN manual_drive_operators o ON c.operator_id=o.id WHERE c.id=?");
            $ci->execute([$catId]); $ci=$ci->fetch();
            notifyPending('manual_drive', $user['name'], ['📡 Operator'=>($ci['op_icon']??'').' '.($ci['op_name']??''),'📂 Category'=>($ci['icon']??'').' '.($ci['name']??''),'📦 Package'=>$pkg?$pkg['name']:$title,'📋 Details'=>substr($detail,0,150),'💰 Amount'=>$amount>0?'৳'.number_format($amount,2):'Free','👤 User'=>$user['name'],'🔖 Ref'=>$ref]);
            $db->commit();
            $success = "✅ Request পাঠানো হয়েছে! Ref: $ref";
        } catch(Exception $e) { $db->rollBack(); $error='Error: '.$e->getMessage(); }
    }
}

$operators = $db->query("SELECT * FROM manual_drive_operators WHERE is_active=1 ORDER BY sort_order,id")->fetchAll();
// Secondary currency
$uc = null;
try {
    if (!empty($user['preferred_currency']) && $user['preferred_currency'] !== 'BDT') {
        $s = $db->prepare("SELECT * FROM currencies WHERE code=? AND is_active=1");
        $s->execute([$user['preferred_currency']]); $uc = $s->fetch() ?: null;
    }
} catch(Exception $e) {}

// User's manual drive commission rate from package
$mdCommRate = 0;
try {
    $r = $db->prepare("SELECT p.manual_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']]);
    $mdCommRate = floatval($r->fetchColumn() ?: 0);
} catch(Exception $e) {}

$allCats   = $db->query("SELECT * FROM manual_drive_categories WHERE is_active=1 ORDER BY sort_order,id")->fetchAll();
$allPkgs   = $db->query("SELECT p.*, o.name as op_name, o.icon as op_icon, o.logo as op_logo, o.color as op_color, o.code as op_code FROM manual_drive_packages p JOIN manual_drive_operators o ON p.operator_id=o.id WHERE p.is_active=1 ORDER BY p.category_id, o.sort_order, p.sort_order, p.id")->fetchAll();

$myReqs = $db->prepare("SELECT r.*, c.name as cat_name, c.icon as cat_icon, o.name as op_name, o.icon as op_icon FROM manual_drive_requests r JOIN manual_drive_categories c ON r.category_id=c.id LEFT JOIN manual_drive_operators o ON c.operator_id=o.id WHERE r.user_id=? ORDER BY r.created_at DESC LIMIT 30");
$myReqs->execute([$user['id']]); $myReqs=$myReqs->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>Manual Drive</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<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;color:#333;padding-bottom:90px}

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

.tabs{display:flex;background:white;border-bottom:1px solid #eee;position:sticky;top:56px;z-index:50}
.tab{flex:1;padding:13px;text-align:center;font-size:13px;font-weight:700;color:#aaa;cursor:pointer;border-bottom:2px solid transparent;transition:0.2s}
.tab.on{color:var(--primary);border-bottom-color:var(--primary)}

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

.alert{padding:12px 16px;border-radius:12px;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}

/* Breadcrumb */
.breadcrumb{display:flex;align-items:center;gap:6px;padding:10px 14px;background:white;border-radius:12px;margin-bottom:14px;font-size:12px;font-weight:600;color:#888;box-shadow:0 1px 4px rgba(0,0,0,0.05);flex-wrap:wrap}
.bc-item{display:flex;align-items:center;gap:4px}
.bc-item.active{color:var(--primary)}
.bc-sep{color:#ddd;font-size:10px}
.bc-step{width:20px;height:20px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:800;flex-shrink:0}
.bc-step.done{background:var(--primary);color:white}
.bc-step.active{background:#e8ecf4;color:var(--primary)}
.bc-step.pending{background:#f0f0f0;color:#ccc}

/* Section card */
.sec{background:white;border-radius:16px;padding:18px;margin-bottom:14px;box-shadow:0 1px 8px rgba(0,0,0,0.06)}
.sec-hd{display:flex;align-items:center;justify-content:space-between;margin-bottom:14px}
.sec-title{font-size:14px;font-weight:800;color:var(--dark);display:flex;align-items:center;gap:8px}
.back-link{display:flex;align-items:center;gap:5px;font-size:12px;color:#888;font-weight:700;cursor:pointer;padding:6px 10px;border-radius:8px;background:#f5f7fa;border:none}
.back-link:hover{background:#e8ecf4}

/* Operator grid */
.op-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:10px}
.op-card{background:white;border-radius:14px;padding:14px 10px 12px;text-align:center;cursor:pointer;border:2px solid #f0f0f0;transition:all 0.2s;box-shadow:0 1px 4px rgba(0,0,0,0.04)}
.op-card:active{transform:scale(0.95)}
.op-card.sel{box-shadow:0 4px 14px rgba(0,0,0,0.1)}
.op-icon{font-size:30px;margin-bottom:6px;line-height:1}
.op-name{font-size:11px;font-weight:700;color:#333;line-height:1.3}
.op-code{font-size:10px;font-weight:700;padding:1px 7px;border-radius:20px;margin-top:4px;display:inline-block}

/* Category list */
.cat-list{display:flex;flex-direction:column;gap:8px}
.cat-item{background:white;border-radius:12px;padding:13px 16px;cursor:pointer;border:2px solid #f0f0f0;display:flex;align-items:center;gap:12px;transition:all 0.2s;box-shadow:0 1px 4px rgba(0,0,0,0.04)}
.cat-item:active{transform:scale(0.98)}
.cat-item.sel,.cat-item:hover{border-color:var(--primary);background:#f0f4ff}
.cat-icon{font-size:22px;flex-shrink:0}
.cat-name{font-size:14px;font-weight:700;color:#333;flex:1}
.cat-count{font-size:11px;color:#aaa}

/* Package list */
.pkg-list{display:flex;flex-direction:column;gap:8px}
.pkg-item{background:white;border-radius:12px;border:2px solid #f0f0f0;padding:14px 16px;cursor:pointer;display:flex;align-items:center;gap:12px;transition:all 0.2s;position:relative;box-shadow:0 1px 4px rgba(0,0,0,0.04)}
.pkg-item:active{transform:scale(0.98)}
.pkg-item.sel{border-color:var(--primary);background:#f0f4ff;box-shadow:0 4px 14px rgba(26,60,143,0.1)}
.pkg-radio{width:22px;height:22px;border-radius:50%;border:2px solid #e8ecf4;background:white;display:flex;align-items:center;justify-content:center;flex-shrink:0;transition:0.2s;font-size:12px;color:transparent}
.pkg-item.sel .pkg-radio{background:var(--primary);border-color:var(--primary);color:white}
.pkg-info{flex:1;min-width:0}
.pkg-name{font-size:13px;font-weight:700;color:#333}
.pkg-desc{font-size:11px;color:#aaa;margin-top:2px}
.pkg-tags{display:flex;gap:6px;margin-top:6px;flex-wrap:wrap}
.pkg-tag{font-size:11px;font-weight:700;padding:2px 10px;border-radius:20px}
.tag-price{background:#ebf4ff;color:var(--primary)}
.tag-comm{background:#f0fff4;color:#276749}
.tag-free{background:#f5f5f5;color:#888}

/* Summary box */
.summary{border-radius:14px;padding:16px;margin-bottom:14px;background:white;border:2px solid #e8ecf4}
.sum-row{display:flex;justify-content:space-between;align-items:center;padding:6px 0;font-size:13px}
.sum-row:not(:last-child){border-bottom:1px solid #f5f5f5}
.sum-lbl{color:#888;display:flex;align-items:center;gap:6px}
.sum-val{font-weight:700;color:#333}

/* Form */
.fg{margin-bottom:14px}
.fg label{display:block;font-size:12px;font-weight:700;color:#666;margin-bottom:6px;text-transform:uppercase;letter-spacing:0.3px}
.fg input,.fg textarea{width:100%;padding:13px 14px;border:2px solid #e8ecf4;border-radius:12px;font-size:14px;outline:none;font-family:inherit;resize:vertical}
.fg input:focus,.fg textarea:focus{border-color:var(--primary)}
.fg textarea{min-height:90px}

.submit-btn{width:100%;padding:16px;background:linear-gradient(135deg,var(--primary),#2856c8);color:white;border:none;border-radius:14px;font-size:15px;font-weight:800;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px;box-shadow:0 4px 16px rgba(26,60,143,0.3);transition:0.2s}
.submit-btn:active{transform:scale(0.98)}

/* History */
.req-card{background:white;border-radius:14px;margin-bottom:10px;overflow:hidden;box-shadow:0 1px 6px rgba(0,0,0,0.06)}
.req-head{display:flex;align-items:center;gap:12px;padding:14px 16px;cursor:pointer}
.req-det{display:none;padding:12px 16px 14px;border-top:1px solid #f5f5f5;background:#fafbff}
.req-det.open{display:block}
.s-badge{font-size:11px;font-weight:700;padding:3px 10px;border-radius:20px}
.s-pending{background:#fffbeb;color:#d69e2e}.s-success{background:#f0fff4;color:#276749}
.s-failed{background:#fff5f5;color:#c53030}.s-processing{background:#ebf8ff;color:#2b6cb0}
.empty{text-align:center;padding:40px;color:#ccc}
.empty i{font-size:36px;display:block;margin-bottom:10px}

@keyframes slideUp{from{opacity:0;transform:translateY(16px)}to{opacity:1;transform:translateY(0)}}
.anim{animation:slideUp 0.3s ease}

/* New category card */
.cat-card-new{background:white;border-radius:16px;border:2px solid #f0f0f0;padding:16px 14px;text-align:center;cursor:pointer;transition:all 0.2s;box-shadow:0 1px 6px rgba(0,0,0,0.05)}
.cat-card-new:active{transform:scale(0.96)}
.cat-card-new.sel,.cat-card-new:hover{border-color:var(--primary);box-shadow:0 4px 16px rgba(26,60,143,0.12);transform:translateY(-2px)}
</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">📦 Manual Drive</div>
        <div class="bal-pill">৳<?= number_format($user['balance'],2) ?></div>
    </div>
</div>

<div class="tabs">
    <div class="tab on" id="tab-new-lbl" onclick="switchTab('new',this)">📝 New Request</div>
    <div class="tab" onclick="switchTab('history',this)">📋 My Requests (<?= count($myReqs) ?>)</div>
</div>

<!-- ===== NEW REQUEST ===== -->
<div id="tab-new">
<div class="page">

<?php if($error): ?><div class="alert alert-err">❌ <?= htmlspecialchars($error) ?></div><?php endif; ?>
<?php if($success): ?><div class="alert alert-ok"><?= htmlspecialchars($success) ?></div><?php endif; ?>

<!-- Breadcrumb -->
<div class="breadcrumb" id="bcBar">
    <div class="bc-item active" id="bc1"><div class="bc-step active" id="bcs1">1</div> Category</div>
    <div class="bc-sep"><i class="fas fa-chevron-right"></i></div>
    <div class="bc-item" id="bc2"><div class="bc-step pending" id="bcs2">2</div> Operator</div>
    <div class="bc-sep"><i class="fas fa-chevron-right"></i></div>
    <div class="bc-item" id="bc3"><div class="bc-step pending" id="bcs3">3</div> Package</div>
    <div class="bc-sep"><i class="fas fa-chevron-right"></i></div>
    <div class="bc-item" id="bc4"><div class="bc-step pending" id="bcs4">4</div> Submit</div>
</div>

<!-- STEP 1: Category -->
<div id="s1" class="anim">
    <div class="sec">
        <div class="sec-title" style="margin-bottom:16px"><i class="fas fa-th-large" style="color:var(--primary)"></i> Select Category</div>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
        <?php foreach($allCats as $cat):
            $catPkgCount = 0;
            foreach($allPkgs as $p) if($p['category_id']==$cat['id']) $catPkgCount++;
        ?>
        <div class="cat-card-new" data-id="<?= $cat['id'] ?>" data-name="<?= htmlspecialchars($cat['name'],ENT_QUOTES) ?>" data-icon="<?= $cat['icon'] ?>" onclick="selCat1(this)" style="border-color:<?= $cat['color'] ?>22">
            <?php if(!empty($cat['logo'])): ?>
            <img src="<?= SITE_URL ?>/<?= htmlspecialchars($cat['logo']) ?>" style="width:52px;height:52px;border-radius:14px;object-fit:contain;background:<?= $cat['color'] ?>18;padding:6px;margin-bottom:10px;display:block;margin-left:auto;margin-right:auto">
            <?php else: ?>
            <div style="width:52px;height:52px;border-radius:14px;background:<?= $cat['color'] ?>18;display:flex;align-items:center;justify-content:center;font-size:28px;margin-bottom:10px;margin:0 auto 10px"><?= $cat['icon'] ?></div>
            <?php endif; ?>
            <div style="font-size:13px;font-weight:800;color:#1a1a2e;margin-bottom:4px"><?= htmlspecialchars($cat['name']) ?></div>
            <div style="font-size:11px;color:#aaa"><?= $catPkgCount ?> packages</div>
            <div style="margin-top:10px;width:100%;height:3px;border-radius:2px;background:<?= $cat['color'] ?>30"></div>
        </div>
        <?php endforeach; ?>
        </div>
    </div>
</div>

<!-- STEP 2: Category -->
<div id="s2" style="display:none">
    <div class="sec anim">
        <div class="sec-hd">
            <div class="sec-title" id="step2Title"><i class="fas fa-sim-card" style="color:var(--primary)"></i> Operator বেছে নিন</div>
            <button class="back-link" onclick="goStep(1)"><i class="fas fa-arrow-left"></i> Back</button>
        </div>
        <div class="cat-list" id="catList"></div>
    </div>
</div>

<!-- STEP 3: Package -->
<div id="s3" style="display:none">
    <div class="sec anim">
        <div class="sec-hd">
            <div class="sec-title"><i class="fas fa-box-open" style="color:var(--primary)"></i> Select Package</div>
            <button class="back-link" onclick="goStep(2)"><i class="fas fa-arrow-left"></i> Back</button>
        </div>
        <!-- Search -->
        <div style="position:relative;margin-bottom:12px">
            <i class="fas fa-search" style="position:absolute;left:13px;top:50%;transform:translateY(-50%);color:#aaa;font-size:13px;pointer-events:none"></i>
            <input type="text" id="pkgSearch" placeholder="Search packages..." oninput="filterPkgs(this.value)"
                style="width:100%;padding:11px 14px 11px 38px;border:2px solid #e8ecf4;border-radius:12px;font-size:13px;outline:none;font-family:inherit">
        </div>
        <div class="pkg-list" id="pkgList"></div>
        <div id="pkgNoResult" style="display:none;text-align:center;padding:20px;color:#ccc;font-size:13px">No packages found</div>
    </div>
</div>

<!-- STEP 4: Submit form -->
<div id="s4" style="display:none">
    <div id="summaryBox" class="summary anim"></div>
    <form method="POST" id="driveForm">
        <input type="hidden" name="submit_drive" value="1">
        <input type="hidden" name="operator_id" id="fOpId">
        <input type="hidden" name="category_id" id="fCatId">
        <input type="hidden" name="package_id"  id="fPkgId">
        <input type="hidden" name="title"        id="fTitle">
        <div class="sec anim">
            <div class="sec-hd">
                <div class="sec-title"><i class="fas fa-mobile-alt" style="color:#805ad5"></i> Phone Number</div>
                <button type="button" class="back-link" onclick="goStep(3)"><i class="fas fa-arrow-left"></i> Back</button>
            </div>
            <div class="fg">
                <label style="font-size:11px;font-weight:700;color:#666;text-transform:uppercase;letter-spacing:0.3px">Mobile Number *</label>
                <div style="position:relative">
                    <i class="fas fa-mobile-alt" style="position:absolute;left:14px;top:50%;transform:translateY(-50%);color:#aaa;font-size:14px"></i>
                    <input type="tel" name="details" id="fPhone" required placeholder="01XXXXXXXXX"
                        style="width:100%;padding:14px 14px 14px 40px;border:2px solid #e8ecf4;border-radius:12px;font-size:16px;outline:none;font-family:monospace;letter-spacing:1px"
                        oninput="updateTitle(this.value)">
                </div>
            </div>
            <!-- Price breakdown with dual currency -->
            <div id="priceBreakdown" style="display:none;background:#f8fafc;border-radius:12px;padding:14px;margin-top:4px">
                <div id="pbRows"></div>
            </div>
        </div>
        <button type="submit" class="submit-btn"><i class="fas fa-paper-plane"></i> Submit Request</button>
    </form>
</div>

</div>
</div>

<!-- ===== HISTORY ===== -->
<div id="tab-history" style="display:none">
<div class="page">
    <?php if(empty($myReqs)): ?>
    <div class="empty"><i class="fas fa-inbox"></i>No requests yet</div>
    <?php else: foreach($myReqs as $r): ?>
    <div class="req-card">
        <div class="req-head" onclick="toggleR(<?= $r['id'] ?>)">
            <div style="width:42px;height:42px;border-radius:12px;background:#f0f4ff;display:flex;align-items:center;justify-content:center;font-size:20px;flex-shrink:0"><?= $r['cat_icon'] ?></div>
            <div style="flex:1;min-width:0">
                <div style="font-size:13px;font-weight:700;color:#333;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?= htmlspecialchars($r['title']) ?></div>
                <div style="font-size:11px;color:#aaa;margin-top:2px"><?= $r['op_icon']??'' ?> <?= htmlspecialchars($r['op_name']??'') ?> · <?= htmlspecialchars($r['cat_name']) ?> · <?= date('d M, h:i A',strtotime($r['created_at'])) ?></div>
            </div>
            <div style="text-align:right;flex-shrink:0;margin-right:6px">
                <div style="font-size:14px;font-weight:800;color:var(--primary)"><?= $r['amount']>0?'৳'.number_format($r['amount'],2):'Free' ?></div>
                <span class="s-badge s-<?= $r['status'] ?>"><?= ucfirst($r['status']) ?></span>
            </div>
            <i class="fas fa-chevron-down" id="rch<?= $r['id'] ?>" style="color:#ddd;font-size:11px;transition:0.2s"></i>
        </div>
        <div class="req-det" id="rdet<?= $r['id'] ?>">
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:10px">
                <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">Reference</div>
                    <div style="font-size:11px;font-weight:700;font-family:monospace;color:#333"><?= $r['reference'] ?></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">Commission</div>
                    <div style="font-size:14px;font-weight:800;color:#276749"><?= $r['commission']>0?'+৳'.number_format($r['commission'],2):'—' ?></div>
                </div>
            </div>
            <div style="background:white;border-radius:8px;padding:10px 12px;font-size:12px;color:#555;border:1px solid #f0f0f0;line-height:1.6;margin-bottom:8px"><?= nl2br(htmlspecialchars($r['details'])) ?></div>
            <?php if($r['admin_note']): ?>
            <div style="background:#fffbeb;border-radius:8px;padding:10px 12px;font-size:12px;color:#744210;border-left:3px solid #d69e2e"><b>Admin Note:</b> <?= htmlspecialchars($r['admin_note']) ?></div>
            <?php endif; ?>
        </div>
    </div>
    <?php endforeach; endif; ?>
</div>
</div>

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

<script>
const CATS = <?= json_encode(array_values($allCats), JSON_UNESCAPED_UNICODE) ?>;
const PKGS = <?= json_encode(array_values($allPkgs),  JSON_UNESCAPED_UNICODE) ?>;
const UC   = <?php echo $uc ? json_encode(['symbol'=>htmlspecialchars($uc['symbol']),'code'=>$uc['code'],'rate'=>floatval($uc['rate'])]) : 'null' ?>;
const MD_COMM_RATE = <?= $mdCommRate ?>;  // User's manual_drive_commission %
function fmtUC(bdt) {
    if(!UC || !UC.rate) return '';
    return ' ≈ '+UC.symbol+parseFloat(bdt*UC.rate).toFixed(2)+' '+UC.code;
}

let sel = {cat:null, op:null, pkg:null};
let curStep = 1;

function goStep(n) {
    for(let i=1;i<=4;i++) document.getElementById('s'+i).style.display = i===n?'block':'none';
    curStep = n;
    updateBC();
    window.scrollTo({top:0,behavior:'smooth'});
}
function updateBC() {
    for(let i=1;i<=4;i++) {
        const bci=document.getElementById('bc'+i), bcs=document.getElementById('bcs'+i);
        if(i<curStep){bci.classList.remove('active');bci.style.opacity='0.6';bcs.className='bc-step done';bcs.innerHTML='✓';}
        else if(i===curStep){bci.classList.add('active');bci.style.opacity='1';bcs.className='bc-step active';bcs.textContent=i;}
        else{bci.classList.remove('active');bci.style.opacity='0.4';bcs.className='bc-step pending';bcs.textContent=i;}
    }
}

// Step 1: Select Category
function selCat1(el) {
    document.querySelectorAll('.cat-card-new').forEach(c=>c.classList.remove('sel'));
    el.classList.add('sel');
    sel.cat = {id:el.dataset.id, name:el.dataset.name, icon:el.dataset.icon};

    // Get unique operators for this category from packages
    const catPkgs = PKGS.filter(p=>p.category_id==sel.cat.id);
    const opMap = {};
    catPkgs.forEach(p=>{
        if(!opMap[p.operator_id]) opMap[p.operator_id]={id:p.operator_id,name:p.op_name,icon:p.op_icon,logo:p.op_logo||'',color:p.op_color,code:p.op_code};
    });
    const ops = Object.values(opMap);

    const list = document.getElementById('catList');
    if(!ops.length) {
        list.innerHTML='<div style="text-align:center;padding:20px;color:#ccc">No operators in this category</div>';
    } else {
        const pkgCount = opId => catPkgs.filter(p=>p.operator_id==opId).length;
        list.innerHTML = ops.map(o=>`
        <div class="cat-item" data-id="${o.id}" data-name="${o.name}" data-icon="${o.icon}" data-color="${o.color}" data-code="${o.code}" onclick="selOp2(this)">
            ${o.logo
                ? `<img src="<?= SITE_URL ?>/${o.logo}" style="width:38px;height:38px;border-radius:10px;object-fit:contain;background:${o.color}18;padding:5px;flex-shrink:0">`
                : `<div style="width:38px;height:38px;border-radius:10px;background:${o.color}20;display:flex;align-items:center;justify-content:center;font-size:20px;flex-shrink:0">${o.icon}</div>`
            }
            <div style="flex:1">
                <div style="font-size:14px;font-weight:700;color:#333">${o.name} <span style="font-size:10px;background:${o.color};color:white;padding:1px 7px;border-radius:20px">${o.code}</span></div>
                <div style="font-size:11px;color:#aaa">${pkgCount(o.id)} packages</div>
            </div>
            <i class="fas fa-chevron-right" style="color:#ddd;font-size:12px"></i>
        </div>`).join('');
    }
    document.getElementById('step2Title').textContent = sel.cat.icon+' '+sel.cat.name+' — Operator';
    setTimeout(()=>goStep(2),100);
}

// Step 2: Select Operator
function selOp2(el) {
    document.querySelectorAll('.cat-item').forEach(c=>c.classList.remove('sel'));
    el.classList.add('sel');
    sel.op = {id:el.dataset.id, name:el.dataset.name, icon:el.dataset.icon, color:el.dataset.color, code:el.dataset.code};

    const pkgs = PKGS.filter(p=>p.category_id==sel.cat.id && p.operator_id==sel.op.id);
    const list = document.getElementById('pkgList');
    if(!pkgs.length) {
        list.innerHTML='<div style="text-align:center;padding:20px;color:#ccc">No packages</div>';
    } else {
        list.innerHTML = pkgs.map(p=>`
        <div class="pkg-item" data-id="${p.id}" data-name="${p.name.replace(/"/g,'&quot;')}" data-price="${p.price}" data-commission="${p.commission}" onclick="selPkg(this)">
            <div class="pkg-radio">✓</div>
            <div class="pkg-info">
                <div class="pkg-name">${p.name}</div>
                ${p.description?`<div class="pkg-desc">${p.description}</div>`:''}
                <div class="pkg-tags">
                    ${parseFloat(p.price)>0?`<span class="pkg-tag tag-price">৳${parseFloat(p.price).toFixed(0)}</span>`:'<span class="pkg-tag tag-free">Free</span>'}
                    ${(()=>{
                        const comm = parseFloat(p.commission);
                        if(comm<=0) return '';
                        const actual = MD_COMM_RATE>0 ? Math.round(comm * MD_COMM_RATE / 100 * 100)/100 : comm;
                        const label  = `+৳${actual.toFixed(0)} Commission`;
                        return `<span class="pkg-tag tag-comm">${label}</span>`;
                    })()}
                </div>
            </div>
        </div>`).join('');
    }
    goStep(3);
}

// Step 3: Select Package
function selPkg(el) {
    document.querySelectorAll('.pkg-item').forEach(p=>p.classList.remove('sel'));
    el.classList.add('sel');
    sel.pkg = {id:el.dataset.id, name:el.dataset.name, price:parseFloat(el.dataset.price), commission:parseFloat(el.dataset.commission)};

    // Actual commission = pkg.commission × user package rate%
    const commBase   = sel.pkg.commission;
    const actualComm = (MD_COMM_RATE>0 && commBase>0) ? Math.round(commBase * MD_COMM_RATE / 100 * 100)/100 : commBase;

    // Summary box
    let html = `
        <div class="sum-row"><span class="sum-lbl">${sel.cat.icon} Category</span><span class="sum-val">${sel.cat.name}</span></div>
        <div class="sum-row"><span class="sum-lbl">${sel.op.icon} Operator</span><span class="sum-val">${sel.op.name} <span style="font-size:10px;background:${sel.op.color};color:white;padding:1px 7px;border-radius:20px">${sel.op.code}</span></span></div>
        <div class="sum-row"><span class="sum-lbl">📦 Package</span><span class="sum-val">${sel.pkg.name}</span></div>`;
    if(sel.pkg.price>0) html+=`<div class="sum-row"><span class="sum-lbl">💰 Price</span><span class="sum-val" style="color:var(--primary)">৳${sel.pkg.price.toFixed(2)}<span style="font-size:11px;color:#aaa;font-weight:400"> ${fmtUC(sel.pkg.price)}</span></span></div>`;
    if(actualComm>0) html+=`<div class="sum-row"><span class="sum-lbl">💸 Commission</span><span class="sum-val" style="color:#276749">+৳${actualComm.toFixed(2)}<span style="font-size:11px;color:#aaa;font-weight:400"> ${fmtUC(actualComm)}</span></span></div>`;
    document.getElementById('summaryBox').innerHTML = html;

    // Price breakdown step 4
    if(sel.pkg.price>0 || actualComm>0) {
        let pb = '';
        if(sel.pkg.price>0) pb+=`<div class="sum-row"><span class="sum-lbl">💰 Price</span><span class="sum-val" style="color:var(--primary)">৳${sel.pkg.price.toFixed(2)} ${fmtUC(sel.pkg.price)}</span></div>`;
        if(actualComm>0) pb+=`<div class="sum-row"><span class="sum-lbl">💸 Commission</span><span class="sum-val" style="color:#276749">+৳${actualComm.toFixed(2)} ${fmtUC(actualComm)}</span></div>`;
        document.getElementById('pbRows').innerHTML = pb;
        document.getElementById('priceBreakdown').style.display = 'block';
    } else {
        document.getElementById('priceBreakdown').style.display = 'none';
    }

    document.getElementById('fOpId').value  = sel.op.id;
    document.getElementById('fCatId').value = sel.cat.id;
    document.getElementById('fPkgId').value = sel.pkg.id;
    document.getElementById('fTitle').value = sel.pkg.name;
    document.getElementById('fPhone').value = '';
    goStep(4);
}

// Package search filter
function filterPkgs(q) {
    q = q.toLowerCase().trim();
    const items = document.querySelectorAll('#pkgList .pkg-item');
    let visible = 0;
    items.forEach(item => {
        const name = (item.dataset.name||'').toLowerCase();
        const desc = (item.querySelector('.pkg-desc')?.textContent||'').toLowerCase();
        const show = !q || name.includes(q) || desc.includes(q);
        item.style.display = show ? 'flex' : 'none';
        if(show) visible++;
    });
    document.getElementById('pkgNoResult').style.display = visible===0 && q ? 'block' : 'none';
}

// Update hidden title from phone input
function updateTitle(phone) {
    const pkg = sel.pkg ? sel.pkg.name : '';
    document.getElementById('fTitle').value = (pkg ? pkg+' — ' : '') + phone;
}

// Tab switch
function switchTab(tab, el) {
    document.querySelectorAll('.tab').forEach(t=>t.classList.remove('on'));
    el.classList.add('on');
    document.getElementById('tab-new').style.display     = tab==='new'     ? 'block' : 'none';
    document.getElementById('tab-history').style.display = tab==='history' ? 'block' : 'none';
}

// History toggle
function toggleR(id) {
    const d=document.getElementById('rdet'+id), c=document.getElementById('rch'+id);
    d.classList.toggle('open'); c.style.transform=d.classList.contains('open')?'rotate(180deg)':'';
}
</script>
<script>document.addEventListener("DOMContentLoaded",function(){ if(window.pageReady) window.pageReady(); });</script>
</body>
</html>
