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

// Tables
try {
    $db->exec("CREATE TABLE IF NOT EXISTS manual_drive_operators (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, code VARCHAR(10) NOT NULL, icon VARCHAR(20) DEFAULT '📡', logo VARCHAR(255) DEFAULT NULL, color VARCHAR(20) DEFAULT '#1a3c8f', is_active TINYINT(1) DEFAULT 1, sort_order INT DEFAULT 0) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
    $db->exec("CREATE TABLE IF NOT EXISTS manual_drive_packages (id INT AUTO_INCREMENT PRIMARY KEY, category_id INT NOT NULL, operator_id INT NOT NULL DEFAULT 0, name VARCHAR(200) NOT NULL, description TEXT, price DECIMAL(10,2) DEFAULT 0, commission DECIMAL(10,2) DEFAULT 0, is_active TINYINT(1) DEFAULT 1, sort_order INT DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
    try { $db->exec("ALTER TABLE manual_drive_packages ADD COLUMN operator_id INT NOT NULL DEFAULT 0 AFTER category_id"); } catch(Exception $e) {}
    try { $db->exec("ALTER TABLE manual_drive_operators ADD COLUMN logo VARCHAR(255) DEFAULT NULL AFTER icon"); } catch(Exception $e) {}
    try { $db->exec("ALTER TABLE manual_drive_categories ADD COLUMN logo VARCHAR(255) DEFAULT NULL AFTER icon"); } catch(Exception $e) {}
    // Set default logos
    $defaultLogos = ['GP'=>'assets/img/operators/gp_logo.svg','BL'=>'assets/img/operators/bl_logo.svg','RB'=>'assets/img/operators/rb_logo.svg','AL'=>'assets/img/operators/al_logo.svg','TT'=>'assets/img/operators/tt_logo.svg'];
    foreach($defaultLogos as $code=>$logo) {
        $db->prepare("UPDATE manual_drive_operators SET logo=? WHERE code=? AND (logo IS NULL OR logo='')")->execute([$logo,$code]);
    }
    if($db->query("SELECT COUNT(*) FROM manual_drive_operators")->fetchColumn()==0)
        $db->exec("INSERT INTO manual_drive_operators (name,code,icon,color,sort_order) VALUES ('Grameenphone','GP','📶','#009B3A',1),('Banglalink','BL','📡','#FF6B00',2),('Robi','RB','🔴','#E4001D',3),('Airtel','AL','🟠','#F7941D',4),('Teletalk','TT','🔵','#1C3F7A',5)");
    if($db->query("SELECT COUNT(*) FROM manual_drive_categories")->fetchColumn()==0)
        $db->exec("INSERT INTO manual_drive_categories (name,icon,color,sort_order) VALUES ('Data Pack','📶','#1a3c8f',1),('Voice Pack','📞','#38a169',2),('Bundle Pack','🎁','#805ad5',3)");
} catch(Exception $e) {}

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

    if ($action === 'save_cat') {
        $id=intval($_POST['cat_id']??0); $name=sanitize($_POST['name']??''); $icon=sanitize($_POST['icon']??'📦'); $color=sanitize($_POST['color']??'#1a3c8f'); $sort=intval($_POST['sort_order']??0); $active=intval($_POST['is_active']??1);
        $logoPath = sanitize($_POST['existing_cat_logo']??'');
        if (!empty($_FILES['cat_logo']['name'])) {
            $ext = strtolower(pathinfo($_FILES['cat_logo']['name'], PATHINFO_EXTENSION));
            if (in_array($ext,['jpg','jpeg','png','svg','webp','gif'])) {
                $dir = '../assets/img/operators/';
                @mkdir($dir, 0755, true);
                $fn = 'mdcat_'.time().'.'.$ext;
                if (move_uploaded_file($_FILES['cat_logo']['tmp_name'], $dir.$fn))
                    $logoPath = 'assets/img/operators/'.$fn;
            }
        }
        if($id) { $db->prepare("UPDATE manual_drive_categories SET name=?,icon=?,logo=?,color=?,sort_order=?,is_active=? WHERE id=?")->execute([$name,$icon,$logoPath?:null,$color,$sort,$active,$id]); $msg=['ok'=>true,'text'=>'Category updated!']; }
        else { $db->prepare("INSERT INTO manual_drive_categories (name,icon,logo,color,sort_order,is_active) VALUES (?,?,?,?,?,?)")->execute([$name,$icon,$logoPath?:null,$color,$sort,$active]); $msg=['ok'=>true,'text'=>'Category added!']; }
    }
    if ($action === 'delete_cat') {
        $id=intval($_POST['cat_id']??0);
        $db->prepare("DELETE FROM manual_drive_packages WHERE category_id=?")->execute([$id]);
        $db->prepare("DELETE FROM manual_drive_categories WHERE id=?")->execute([$id]);
        $msg=['ok'=>true,'text'=>'Deleted!']; header('Location: manual_drive.php'); exit;
    }

    if ($action === 'save_op') {
        $id=intval($_POST['op_id']??0); $name=sanitize($_POST['op_name']??''); $code=strtoupper(sanitize($_POST['op_code']??'')); $icon=sanitize($_POST['op_icon']??'📡'); $color=sanitize($_POST['op_color']??'#1a3c8f'); $sort=intval($_POST['op_sort']??0); $active=intval($_POST['op_active']??1);
        // Logo upload
        $logoPath = sanitize($_POST['existing_logo']??'');
        if (!empty($_FILES['op_logo']['name'])) {
            $ext = strtolower(pathinfo($_FILES['op_logo']['name'], PATHINFO_EXTENSION));
            if (in_array($ext,['jpg','jpeg','png','svg','webp','gif'])) {
                $dir = '../assets/img/operators/';
                @mkdir($dir, 0755, true);
                $fn = 'mdop_'.strtolower($code).'_'.time().'.'.$ext;
                if (move_uploaded_file($_FILES['op_logo']['tmp_name'], $dir.$fn))
                    $logoPath = 'assets/img/operators/'.$fn;
            }
        }
        if($id) { $db->prepare("UPDATE manual_drive_operators SET name=?,code=?,icon=?,logo=?,color=?,sort_order=?,is_active=? WHERE id=?")->execute([$name,$code,$icon,$logoPath?:null,$color,$sort,$active,$id]); $msg=['ok'=>true,'text'=>'Operator updated!']; }
        else { $db->prepare("INSERT INTO manual_drive_operators (name,code,icon,logo,color,sort_order,is_active) VALUES (?,?,?,?,?,?,?)")->execute([$name,$code,$icon,$logoPath?:null,$color,$sort,$active]); $msg=['ok'=>true,'text'=>'Operator added!']; }
    }
    if ($action === 'delete_op') {
        $id=intval($_POST['op_id']??0); $catId=intval($_POST['cat_id_ctx']??0);
        $db->prepare("DELETE FROM manual_drive_packages WHERE operator_id=? AND category_id=?")->execute([$id,$catId]);
        $msg=['ok'=>true,'text'=>'Operator deleted!'];
        if($catId) { header("Location: manual_drive.php?view=operators&cat=$catId"); exit; }
    }

    if ($action === 'save_pkg') {
        $id=intval($_POST['pkg_id']??0); $catId=intval($_POST['pkg_cat_id']??0); $opId=intval($_POST['pkg_op_id']??0);
        $name=sanitize($_POST['pkg_name']??''); $desc=sanitize($_POST['pkg_desc']??'');
        $price=floatval($_POST['pkg_price']??0); $comm=floatval($_POST['pkg_commission']??0);
        $sort=intval($_POST['pkg_sort']??0); $active=intval($_POST['pkg_active']??1);
        if(!$name){$msg=['ok'=>false,'text'=>'Name required!'];}
        elseif($id){$db->prepare("UPDATE manual_drive_packages SET category_id=?,operator_id=?,name=?,description=?,price=?,commission=?,sort_order=?,is_active=? WHERE id=?")->execute([$catId,$opId,$name,$desc,$price,$comm,$sort,$active,$id]);$msg=['ok'=>true,'text'=>'Package updated!'];}
        else{$db->prepare("INSERT INTO manual_drive_packages (category_id,operator_id,name,description,price,commission,sort_order,is_active) VALUES (?,?,?,?,?,?,?,?)")->execute([$catId,$opId,$name,$desc,$price,$comm,$sort,$active]);$msg=['ok'=>true,'text'=>'Package added!'];}
    }
    if ($action === 'bulk_pkg') {
        $ids=array_map('intval',$_POST['ids']??[]); $bulkAct=$_POST['bulk_action']??'';
        if($ids && $bulkAct) {
            $ph=implode(',',array_fill(0,count($ids),'?'));
            if($bulkAct==='delete'){$db->prepare("DELETE FROM manual_drive_packages WHERE id IN ($ph)")->execute($ids);$msg=['ok'=>true,'text'=>'Deleted!'];}
            elseif(in_array($bulkAct,['active','inactive'])){$v=$bulkAct==='active'?1:0;$db->prepare("UPDATE manual_drive_packages SET is_active=? WHERE id IN ($ph)")->execute(array_merge([$v],$ids));$msg=['ok'=>true,'text'=>'Updated!'];}
        }
    }

    // Request actions
    if (in_array($action, ['approve','reject','processing'])) {
        $id=intval($_POST['req_id']??0); $note=sanitize($_POST['admin_note']??''); $comm=floatval($_POST['commission']??0);
        $req=$db->prepare("SELECT r.*, u.name as uname, u.phone as uphone, c.name as cat_name, c.icon as cat_icon FROM manual_drive_requests r JOIN users u ON r.user_id=u.id JOIN manual_drive_categories c ON r.category_id=c.id WHERE r.id=?");
        $req->execute([$id]); $req=$req->fetch();
        if($req){
            if($action==='approve'){
                $db->beginTransaction();
                try{
                    if($comm<=0){
                        // Get user's package rate
                        $pr=$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=?");
                        $pr->execute([$req['user_id']]);
                        $rate=floatval($pr->fetchColumn()?:0);
                        if($rate>0) {
                            // Base = package's own commission field (not amount)
                            $pkgComm = 0;
                            if($req['package_id']) {
                                $pc=$db->prepare("SELECT commission FROM manual_drive_packages WHERE id=?");
                                $pc->execute([$req['package_id']]);
                                $pkgComm=floatval($pc->fetchColumn()?:0);
                            }
                            // If package has commission field, use it; else use amount
                            $base = $pkgComm>0 ? $pkgComm : floatval($req['amount']??0);
                            if($base>0) $comm=round($base*$rate/100,2);
                        }
                    }
                    $db->prepare("UPDATE manual_drive_requests SET status='success',admin_note=?,commission=? WHERE id=?")->execute([$note,$comm,$id]);
                    // Update transaction status too
                    $db->prepare("UPDATE transactions SET status='success' WHERE reference=? AND type='manual_drive'")->execute([$req['reference']]);
                    if($comm>0){$db->prepare("UPDATE users SET balance=balance+? WHERE id=?")->execute([$comm,$req['user_id']]);$cbRef='MDC'.strtoupper(substr(uniqid(),7));$nb=floatval($db->query("SELECT balance FROM users WHERE id={$req['user_id']}")->fetchColumn());$db->prepare("INSERT INTO transactions (user_id,type,amount,charge,net_amount,balance_before,balance_after,reference,status,note) VALUES (?,?,?,0,?,?,?,?,?,?)")->execute([$req['user_id'],'commission',$comm,$comm,$nb-$comm,$nb,$cbRef,'success','Manual Drive: '.$req['reference']]);$db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'success')")->execute([$req['user_id'],'💸 Commission!','৳'.number_format($comm,2).' commission added.']);}
                    $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'success')")->execute([$req['user_id'],'✅ Drive Approved!',$req['cat_icon'].' '.$req['title'].' approved.']);
                    $db->commit();
                    notifyUser($req['user_id'],'Drive Approved! ✅',['📦'=>$req['title'],'💸 Commission'=>$comm>0?'+৳'.number_format($comm,2):'—','📋 Note'=>$note?:'—','🔖'=>$req['reference']]);
                    $msg=['ok'=>true,'text'=>'✅ Approved!'];
                }catch(Exception $e){$db->rollBack();$msg=['ok'=>false,'text'=>$e->getMessage()];}
            }elseif($action==='reject'){
                $db->beginTransaction();
                try{
                    $db->prepare("UPDATE manual_drive_requests SET status='failed',admin_note=? WHERE id=?")->execute([$note,$id]);
                    $db->prepare("UPDATE transactions SET status='failed' WHERE reference=? AND type='manual_drive'")->execute([$req['reference']]);
                    if($req['amount']>0){$db->prepare("UPDATE users SET balance=balance+? WHERE id=?")->execute([$req['amount'],$req['user_id']]);$rr='MRF'.strtoupper(substr(uniqid(),7));$nb=floatval($db->query("SELECT balance FROM users WHERE id={$req['user_id']}")->fetchColumn());$db->prepare("INSERT INTO transactions (user_id,type,amount,charge,net_amount,balance_before,balance_after,reference,status,note) VALUES (?,?,?,0,?,?,?,?,?,?)")->execute([$req['user_id'],'refund',$req['amount'],$req['amount'],$nb-$req['amount'],$nb,$rr,'success','Refund: '.$req['reference']]);}
                    $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'error')")->execute([$req['user_id'],'❌ Drive Rejected',$req['title'].($req['amount']>0?' — ৳'.number_format($req['amount'],2).' refunded':'')]);
                    $db->commit();
                    notifyUser($req['user_id'],'Drive Rejected ❌',['📦'=>$req['title'],'💬 Reason'=>$note?:'—']);
                    $msg=['ok'=>true,'text'=>'Rejected!'];
                }catch(Exception $e){$db->rollBack();$msg=['ok'=>false,'text'=>$e->getMessage()];}
            }elseif($action==='processing'){
                $db->prepare("UPDATE manual_drive_requests SET status='processing',admin_note=? WHERE id=?")->execute([$note,$id]);
                $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'info')")->execute([$req['user_id'],'🔄 Processing',$req['title']]);
                $msg=['ok'=>true,'text'=>'Processing!'];
            }
        }
    }
}

// Determine view
$view  = $_GET['view']  ?? 'categories';
$catId = intval($_GET['cat'] ?? 0);
$opId  = intval($_GET['op']  ?? 0);

// Load based on view
$categories = $db->query("SELECT c.*, (SELECT COUNT(DISTINCT operator_id) FROM manual_drive_packages WHERE category_id=c.id) as op_count, (SELECT COUNT(*) FROM manual_drive_packages WHERE category_id=c.id) as pkg_count FROM manual_drive_categories c ORDER BY c.sort_order,c.id")->fetchAll();

$currentCat = null; $currentOp = null;
if($catId) { $s=$db->prepare("SELECT * FROM manual_drive_categories WHERE id=?"); $s->execute([$catId]); $currentCat=$s->fetch(); }

$operators = [];
if($view === 'operators' && $catId) {
    // Operators that have packages in this category OR all operators for adding
    $operators = $db->query("SELECT o.*, (SELECT COUNT(*) FROM manual_drive_packages WHERE operator_id=o.id AND category_id=$catId) as pkg_count FROM manual_drive_operators o ORDER BY sort_order,id")->fetchAll();
}

$packages = [];
if($view === 'packages' && $catId && $opId) {
    $s=$db->prepare("SELECT * FROM manual_drive_operators WHERE id=?"); $s->execute([$opId]); $currentOp=$s->fetch();
    $s=$db->prepare("SELECT * FROM manual_drive_packages WHERE category_id=? AND operator_id=? ORDER BY sort_order,id"); $s->execute([$catId,$opId]); $packages=$s->fetchAll();
}

// Requests
$statusFilter = $_GET['status'] ?? 'pending';
$where=$statusFilter!=='all'?"WHERE r.status=?":"WHERE 1=1";
$params=$statusFilter!=='all'?[$statusFilter]:[];
$requests=$db->prepare("SELECT r.*, u.name as uname, u.phone as uphone, c.name as cat_name, c.icon as cat_icon FROM manual_drive_requests r JOIN users u ON r.user_id=u.id JOIN manual_drive_categories c ON r.category_id=c.id $where ORDER BY r.created_at DESC LIMIT 100");
$requests->execute($params); $requests=$requests->fetchAll();
$counts=['pending'=>$db->query("SELECT COUNT(*) FROM manual_drive_requests WHERE status='pending'")->fetchColumn(),'processing'=>$db->query("SELECT COUNT(*) FROM manual_drive_requests WHERE status='processing'")->fetchColumn(),'success'=>$db->query("SELECT COUNT(*) FROM manual_drive_requests WHERE status='success'")->fetchColumn(),'failed'=>$db->query("SELECT COUNT(*) FROM manual_drive_requests WHERE status='failed'")->fetchColumn()];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Manual Drive — Admin</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="../assets/css/admin.css">
<style>
.card{background:white;border-radius:14px;box-shadow:0 2px 8px rgba(0,0,0,0.06);margin-bottom:16px;overflow:hidden}
.card-h{padding:14px 18px;font-size:14px;font-weight:700;border-bottom:1px solid #f5f5f5;display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap}
.card-b{padding:16px}
.btn{padding:8px 14px;border:none;border-radius:9px;font-size:12px;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:5px;transition:0.15s;text-decoration:none}
.btn-primary{background:var(--primary);color:white}.btn-ok{background:#f0fff4;color:#276749}.btn-fail{background:#fff5f5;color:#e53e3e}.btn-proc{background:#ebf8ff;color:#2b6cb0}
.btn-sm{padding:6px 10px;font-size:12px;border-radius:8px;border:none;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:4px}
.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}
.breadcrumb{display:flex;align-items:center;gap:8px;font-size:13px;margin-bottom:16px;flex-wrap:wrap}
.bc-link{color:var(--primary);text-decoration:none;font-weight:600}
.bc-link:hover{text-decoration:underline}
.bc-sep{color:#ccc}
.bc-cur{font-weight:700;color:#333}
.pill{padding:7px 14px;border-radius:20px;font-size:12px;font-weight:700;text-decoration:none;display:inline-block}
.pill.active{background:#f0f4ff;color:var(--primary);border:2px solid var(--primary)}.pill:not(.active){background:#f5f5f5;color:#555;border:2px solid transparent}

/* Category grid */
.cat-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:12px}
.cat-card{background:white;border-radius:14px;border:2px solid #f0f0f0;overflow:hidden;transition:0.2s;box-shadow:0 1px 6px rgba(0,0,0,0.04)}
.cat-card:hover{border-color:var(--primary);box-shadow:0 4px 16px rgba(26,60,143,0.1);transform:translateY(-1px)}
.cat-card-body{padding:18px 16px;cursor:pointer;text-decoration:none;display:block}
.cat-card-icon{font-size:32px;margin-bottom:10px;line-height:1}
.cat-card-name{font-size:14px;font-weight:800;color:#1a1a2e;margin-bottom:4px}
.cat-card-meta{font-size:11px;color:#aaa}
.cat-card-actions{border-top:1px solid #f5f5f5;padding:10px 16px;display:flex;gap:8px;background:#fafbfc}

/* Operator grid */
.op-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:10px}
.op-card{background:white;border-radius:12px;border:2px solid #f0f0f0;overflow:hidden;transition:0.2s;box-shadow:0 1px 4px rgba(0,0,0,0.04)}
.op-card:hover{box-shadow:0 4px 14px rgba(0,0,0,0.1);transform:translateY(-1px)}
.op-card-body{padding:16px 14px;cursor:pointer;text-decoration:none;display:block}
.op-card-actions{border-top:1px solid #f5f5f5;padding:8px 12px;display:flex;gap:6px;background:#fafbfc}

/* Package table (drive style) */
.pkg-table{width:100%;border-collapse:collapse}
.pkg-table th{padding:10px 14px;font-size:11px;font-weight:700;color:#888;text-transform:uppercase;letter-spacing:0.5px;border-bottom:2px solid #f0f0f0;text-align:left;background:#fafbfc}
.pkg-table td{padding:12px 14px;border-bottom:1px solid #f5f5f5;font-size:13px;vertical-align:middle}
.pkg-table tr:last-child td{border-bottom:none}
.pkg-table tr:hover td{background:#fafbff}
.pkg-badge{display:inline-block;padding:3px 10px;border-radius:20px;font-size:11px;font-weight:700}
.badge-active{background:#f0fff4;color:#276749}.badge-inactive{background:#f5f5f5;color:#aaa}
.pkg-price{font-size:15px;font-weight:800;color:var(--primary)}
.pkg-comm{background:#f0fff4;color:#276749;padding:3px 10px;border-radius:20px;font-size:12px;font-weight:700}

/* Bulk bar */
.bulk-bar{background:var(--primary);color:white;padding:10px 16px;border-radius:10px;display:none;align-items:center;gap:8px;margin-bottom:12px;flex-wrap:wrap}
.bulk-bar.show{display:flex}
.bulk-btn{padding:6px 12px;border:none;border-radius:8px;font-size:12px;font-weight:700;cursor:pointer}

/* Request */
.req-card{background:white;border-radius:12px;margin-bottom:10px;overflow:hidden;border:1px solid #f0f0f0}
.req-head{display:flex;align-items:center;gap:12px;padding:14px 16px;cursor:pointer}
.req-det{display:none;padding:14px 16px;border-top:1px solid #f5f5f5;background:#fafbff}
.req-det.open{display:block}
.dg{display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;margin-bottom:12px}
.dg-i{background:white;border-radius:8px;padding:9px 12px;border:1px solid #f0f0f0}
.dg-l{font-size:10px;color:#aaa;text-transform:uppercase;margin-bottom:3px}
.dg-v{font-size:12px;font-weight:700;color:#333}
.note-in{width:100%;padding:10px 12px;border:2px solid #e8ecf4;border-radius:9px;font-size:13px;outline:none;font-family:inherit;margin-bottom:8px}
.act-row{display:flex;gap:8px;flex-wrap:wrap}
.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:#e53e3e}.s-processing{background:#ebf8ff;color:#2b6cb0}

/* Modal */
.modal-bg{visibility:hidden;opacity:0;position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:99999;display:flex;align-items:center;justify-content:center;padding:16px;transition:opacity 0.25s;pointer-events:none}
.modal-box{background:white;border-radius:18px;width:100%;max-width:460px;padding:24px;max-height:90vh;overflow-y:auto;transform:scale(0.95);transition:transform 0.25s}
.modal-bg.show{visibility:visible;opacity:1;pointer-events:auto}
.modal-bg.show .modal-box{transform:scale(1)}
.modal-title{font-size:16px;font-weight:800;color:#1a1a2e;margin-bottom:18px;display:flex;align-items:center;justify-content:space-between}
.close-btn{background:#f5f5f5;border:none;width:30px;height:30px;border-radius:50%;font-size:14px;cursor:pointer;color:#666;display:flex;align-items:center;justify-content:center}
.modal-footer{display:flex;gap:8px;justify-content:flex-end;margin-top:16px;padding-top:14px;border-top:1px solid #f0f0f0}
.fg{margin-bottom:12px}
.fg label{display:block;font-size:11px;font-weight:700;color:#666;text-transform:uppercase;margin-bottom:5px}
.fg input,.fg select{width:100%;padding:10px 12px;border:2px solid #e8ecf4;border-radius:10px;font-size:13px;outline:none;font-family:inherit}
.fg input:focus,.fg select:focus{border-color:var(--primary)}
.frow2{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.frow3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px}
.sep{font-size:11px;font-weight:700;color:#888;text-transform:uppercase;border-bottom:1px solid #f0f0f0;padding-bottom:6px;margin:14px 0 10px}
</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">📦 Manual Drive</span>
    </div>
    <div class="topbar-right">
        <a href="<?= SITE_URL ?>/manual-drive.php" target="_blank" class="btn btn-sm" style="background:#f0f4ff;color:var(--primary)"><i class="fas fa-external-link-alt"></i> User Page</a>
        <?php if($view==='categories'): ?><button class="btn btn-primary btn-sm" id="addCatBtn"><i class="fas fa-plus"></i> Category</button><?php endif; ?>
        <?php if($view==='operators' && $catId): ?><button class="btn btn-primary btn-sm" id="addOpBtn"><i class="fas fa-plus"></i> Operator</button><?php endif; ?>
        <?php if($view==='packages' && $catId && $opId): ?><button class="btn btn-primary btn-sm" id="addPkgBtn"><i class="fas fa-plus"></i> Package</button><?php endif; ?>
        <?php if($view==='requests'): ?>
        <a href="?view=categories" class="btn btn-sm" style="background:#f0f4ff;color:var(--primary)"><i class="fas fa-th-large"></i> Categories</a>
        <?php endif; ?>
    </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; ?>

<!-- Stats (always visible) -->
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:16px">
<?php foreach([['⏳','Pending',$counts['pending'],'#fffbeb','#d69e2e'],['🔄','Processing',$counts['processing'],'#ebf8ff','#2b6cb0'],['✅','Success',$counts['success'],'#f0fff4','#276749'],['❌','Failed',$counts['failed'],'#fff5f5','#e53e3e']] as $s): ?>
<div style="background:<?= $s[3] ?>;border-radius:12px;padding:14px;text-align:center;cursor:pointer" onclick="window.location='?view=requests&status=<?= strtolower($s[1]) ?>'">
    <div style="font-size:22px;font-weight:800;color:<?= $s[4] ?>"><?= $s[2] ?></div>
    <div style="font-size:11px;color:<?= $s[4] ?>;opacity:0.8"><?= $s[0] ?> <?= $s[1] ?></div>
</div>
<?php endforeach; ?>
</div>

<!-- Breadcrumb -->
<div class="breadcrumb">
    <a href="?view=categories" class="bc-link"><i class="fas fa-th-large"></i> Categories</a>
    <?php if($view==='operators' && $currentCat): ?>
    <span class="bc-sep">›</span>
    <span class="bc-cur"><?= $currentCat['icon'] ?> <?= htmlspecialchars($currentCat['name']) ?></span>
    <?php elseif($view==='packages' && $currentCat && $currentOp): ?>
    <span class="bc-sep">›</span>
    <a href="?view=operators&cat=<?= $catId ?>" class="bc-link"><?= $currentCat['icon'] ?> <?= htmlspecialchars($currentCat['name']) ?></a>
    <span class="bc-sep">›</span>
    <span class="bc-cur"><?= $currentOp['icon'] ?> <?= htmlspecialchars($currentOp['name']) ?></span>
    <?php elseif($view==='requests'): ?>
    <span class="bc-sep">›</span>
    <span class="bc-cur">📋 Requests</span>
    <?php endif; ?>
    <span style="margin-left:auto"><a href="?view=requests" class="btn btn-sm" style="background:#fffbeb;color:#d69e2e"><i class="fas fa-inbox"></i> Requests (<?= $counts['pending'] ?> pending)</a></span>
</div>

<?php if($view==='categories'): ?>
<!-- ===== CATEGORIES VIEW ===== -->
<div class="card">
    <div class="card-h"><span><i class="fas fa-th-large" style="color:var(--primary)"></i> Categories</span><span style="font-size:12px;color:#aaa"><?= count($categories) ?> total</span></div>
    <div class="card-b">
    <?php if(empty($categories)): ?>
    <div style="text-align:center;padding:40px;color:#ccc"><i class="fas fa-folder-open" style="font-size:36px;display:block;margin-bottom:10px"></i>No categories. Click <b>+ Category</b></div>
    <?php else: ?>
    <div class="cat-grid">
    <?php foreach($categories as $c): ?>
    <div class="cat-card">
        <a href="?view=operators&cat=<?= $c['id'] ?>" class="cat-card-body" style="text-decoration:none">
            <?php if(!empty($c['logo'])): ?>
            <img src="<?= SITE_URL ?>/<?= htmlspecialchars($c['logo']) ?>" style="width:52px;height:52px;border-radius:14px;object-fit:contain;background:<?= $c['color'] ?>18;padding:6px;margin-bottom:10px;display:block">
            <?php else: ?>
            <div class="cat-card-icon"><?= $c['icon'] ?></div>
            <?php endif; ?>
            <div class="cat-card-name"><?= htmlspecialchars($c['name']) ?></div>
            <div class="cat-card-meta"><?= $c['op_count'] ?> operators · <?= $c['pkg_count'] ?> packages</div>
            <div style="margin-top:10px;display:flex;align-items:center;gap:6px">
                <span style="font-size:11px;background:<?= $c['is_active']?'#f0fff4':'#f5f5f5' ?>;color:<?= $c['is_active']?'#276749':'#aaa' ?>;padding:2px 9px;border-radius:20px;font-weight:700"><?= $c['is_active']?'✅ Active':'❌ Inactive' ?></span>
                <span style="font-size:11px;color:#ccc;margin-left:auto"><i class="fas fa-chevron-right"></i></span>
            </div>
        </a>
        <div class="cat-card-actions">
            <button class="btn-sm" style="background:#ebf8ff;color:var(--primary)" onclick='openCatM(<?= htmlspecialchars(json_encode($c),ENT_QUOTES) ?>)'><i class="fas fa-edit" style="pointer-events:none;font-size:11px"></i> Edit</button>
            <form method="POST" style="display:inline" onsubmit="return confirm('Delete category and all packages?')">
                <input type="hidden" name="action" value="delete_cat">
                <input type="hidden" name="cat_id" value="<?= $c['id'] ?>">
                <button type="submit" class="btn-sm" style="background:#fff5f5;color:#e53e3e"><i class="fas fa-trash" style="font-size:11px"></i></button>
            </form>
        </div>
    </div>
    <?php endforeach; ?>
    </div>
    <?php endif; ?>
    </div>
</div>

<?php elseif($view==='operators' && $catId && $currentCat): ?>
<!-- ===== OPERATORS VIEW ===== -->
<div class="card">
    <div class="card-h">
        <span><i class="fas fa-sim-card" style="color:var(--primary)"></i> <?= $currentCat['icon'] ?> <?= htmlspecialchars($currentCat['name']) ?> — Operators</span>
        <span style="font-size:12px;color:#aaa"><?= count($operators) ?> operators</span>
    </div>
    <div class="card-b">
    <?php if(empty($operators)): ?>
    <div style="text-align:center;padding:40px;color:#ccc"><i class="fas fa-sim-card" style="font-size:36px;display:block;margin-bottom:10px"></i>No operators. Click <b>+ Operator</b></div>
    <?php else: ?>
    <div class="op-grid">
    <?php foreach($operators as $op): ?>
    <div class="op-card">
        <a href="?view=packages&cat=<?= $catId ?>&op=<?= $op['id'] ?>" class="op-card-body" style="text-decoration:none">
            <?php if($op['logo']): ?>
            <img src="<?= SITE_URL ?>/<?= htmlspecialchars($op['logo']) ?>" alt="<?= htmlspecialchars($op['name']) ?>"
                style="width:48px;height:48px;border-radius:12px;object-fit:contain;background:<?= $op['color'] ?>18;padding:6px;margin-bottom:10px;display:block">
            <?php else: ?>
            <div style="width:48px;height:48px;border-radius:12px;background:<?= $op['color'] ?>22;display:flex;align-items:center;justify-content:center;font-size:24px;margin-bottom:10px"><?= $op['icon'] ?></div>
            <?php endif; ?>
            <div style="font-size:14px;font-weight:800;color:#1a1a2e;margin-bottom:4px"><?= htmlspecialchars($op['name']) ?></div>
            <div style="display:inline-block;background:<?= $op['color'] ?>;color:white;font-size:10px;font-weight:700;padding:2px 9px;border-radius:20px;margin-bottom:6px"><?= $op['code'] ?></div>
            <div style="font-size:11px;color:#aaa"><?= $op['pkg_count'] ?> packages <i class="fas fa-chevron-right" style="margin-left:4px;font-size:10px"></i></div>
        </a>
        <div class="op-card-actions">
            <button class="btn-sm" style="background:#ebf8ff;color:var(--primary)" onclick='openOpM(<?= htmlspecialchars(json_encode($op),ENT_QUOTES) ?>)'><i class="fas fa-edit" style="pointer-events:none;font-size:11px"></i></button>
        </div>
    </div>
    <?php endforeach; ?>
    </div>
    <?php endif; ?>
    </div>
</div>

<?php elseif($view==='packages' && $catId && $opId && $currentCat && $currentOp): ?>
<!-- ===== PACKAGES VIEW (Drive style) ===== -->
<div class="card">
    <div class="card-h">
        <span>
            <span style="background:<?= $currentOp['color'] ?>22;color:<?= $currentOp['color'] ?>;padding:3px 10px;border-radius:20px;font-weight:800;font-size:12px;margin-right:6px"><?= $currentOp['code'] ?></span>
            <?= $currentOp['icon'] ?> <?= htmlspecialchars($currentOp['name']) ?> — <?= $currentCat['icon'] ?> <?= htmlspecialchars($currentCat['name']) ?>
        </span>
        <span style="font-size:12px;color:#aaa"><?= count($packages) ?> packages</span>
    </div>

    <?php if(!empty($packages)): ?>
    <!-- Bulk bar -->
    <div style="padding:10px 16px;border-bottom:1px solid #f5f5f5">
        <div class="bulk-bar" id="pkgBulk">
            <span style="font-size:13px;font-weight:700;flex:1" id="pkgBulkCnt">0 selected</span>
            <button class="bulk-btn" style="background:#f0fff4;color:#276749" onclick="doBulk('active')">✅ Active</button>
            <button class="bulk-btn" style="background:#fffbeb;color:#d69e2e" onclick="doBulk('inactive')">❌ Inactive</button>
            <button class="bulk-btn" style="background:#fff5f5;color:#e53e3e" onclick="doBulk('delete')">🗑️ Delete</button>
            <button class="bulk-btn" style="background:rgba(255,255,255,0.2);color:white" onclick="clearSel()">✕</button>
        </div>
        <label style="display:flex;align-items:center;gap:8px;font-size:12px;font-weight:700;color:#666;cursor:pointer">
            <input type="checkbox" id="saAll" onchange="tAll(this.checked)" style="width:15px;height:15px;accent-color:var(--primary)"> Select All
        </label>
    </div>
    <?php endif; ?>

    <div class="card-b" style="padding:0">
    <?php if(empty($packages)): ?>
    <div style="text-align:center;padding:40px;color:#ccc"><i class="fas fa-box-open" style="font-size:36px;display:block;margin-bottom:10px"></i>No packages. Click <b>+ Package</b></div>
    <?php else: ?>
    <div style="overflow-x:auto">
    <table class="pkg-table">
        <thead>
            <tr>
                <th style="width:30px"></th>
                <th>Package Name</th>
                <th>Price</th>
                <th>Commission</th>
                <th>Description</th>
                <th>Status</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach($packages as $p): ?>
        <tr>
            <td><input type="checkbox" class="pkg-cb" value="<?= $p['id'] ?>" onchange="updBulk()" style="width:15px;height:15px;accent-color:var(--primary)"></td>
            <td><strong style="font-size:13px;color:#1a1a2e"><?= htmlspecialchars($p['name']) ?></strong></td>
            <td><?php if($p['price']>0): ?><span class="pkg-price">৳<?= number_format($p['price'],2) ?></span><?php else: ?><span style="color:#aaa;font-size:12px">Free</span><?php endif; ?></td>
            <td><?php if($p['commission']>0): ?><span class="pkg-comm">+৳<?= number_format($p['commission'],0) ?></span><?php else: ?><span style="color:#ddd">—</span><?php endif; ?></td>
            <td style="font-size:12px;color:#888;max-width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?= htmlspecialchars($p['description']??'—') ?></td>
            <td><span class="pkg-badge <?= $p['is_active']?'badge-active':'badge-inactive' ?>"><?= $p['is_active']?'✅ Active':'❌ Inactive' ?></span></td>
            <td>
                <div style="display:flex;gap:6px">
                    <button class="btn-sm" style="background:#ebf8ff;color:var(--primary)" onclick='openPkgM(<?= htmlspecialchars(json_encode($p),ENT_QUOTES) ?>)'><i class="fas fa-edit" style="font-size:11px;pointer-events:none"></i> Edit</button>
                    <form method="POST" onsubmit="return confirm('Delete?')" style="display:inline">
                        <input type="hidden" name="action" value="bulk_pkg">
                        <input type="hidden" name="bulk_action" value="delete">
                        <input type="hidden" name="ids[]" value="<?= $p['id'] ?>">
                        <button type="submit" class="btn-sm" style="background:#fff5f5;color:#e53e3e"><i class="fas fa-trash" style="font-size:11px"></i></button>
                    </form>
                </div>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>
    <?php endif; ?>
    </div>
</div>

<?php elseif($view==='requests'): ?>
<!-- ===== REQUESTS ===== -->
<div class="card">
    <div class="card-h"><i class="fas fa-inbox" style="color:var(--primary)"></i> Requests</div>
    <div style="padding:12px 16px;border-bottom:1px solid #f5f5f5;display:flex;gap:8px;flex-wrap:wrap">
        <?php foreach(['pending'=>'⏳ Pending','processing'=>'🔄 Processing','success'=>'✅ Success','failed'=>'❌ Failed','all'=>'📋 All'] as $s=>$l): ?>
        <a href="?view=requests&status=<?= $s ?>" class="pill <?= $statusFilter===$s?'active':'' ?>"><?= $l ?> (<?= $s==='all'?array_sum($counts):($counts[$s]??0) ?>)</a>
        <?php endforeach; ?>
    </div>
    <div style="padding:12px 16px">
    <?php if(empty($requests)): ?><div style="text-align:center;padding:30px;color:#ccc">No requests</div>
    <?php else: foreach($requests as $r): ?>
    <div class="req-card">
        <div class="req-head" onclick="tR(<?= $r['id'] ?>)">
            <div style="width:38px;height:38px;border-radius:10px;background:#f0f4ff;display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0"><?= $r['cat_icon'] ?></div>
            <div style="flex:1;min-width:0">
                <div style="font-size:13px;font-weight:700;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?= htmlspecialchars($r['title']) ?></div>
                <div style="font-size:11px;color:#aaa">👤 <?= htmlspecialchars($r['uname']) ?> · <?= htmlspecialchars($r['cat_name']) ?> · <?= date('d M, h:i A',strtotime($r['created_at'])) ?></div>
            </div>
            <div style="text-align:right;flex-shrink:0">
                <div style="font-size:13px;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;margin-left:6px;transition:0.2s"></i>
        </div>
        <div class="req-det" id="rdet<?= $r['id'] ?>">
            <div class="dg">
                <div class="dg-i"><div class="dg-l">User</div><div class="dg-v"><?= htmlspecialchars($r['uname']) ?></div></div>
                <div class="dg-i"><div class="dg-l">Phone</div><div class="dg-v"><?= $r['uphone']??'—' ?></div></div>
                <div class="dg-i"><div class="dg-l">Ref</div><div class="dg-v" style="font-size:11px;font-family:monospace"><?= $r['reference'] ?></div></div>
                <div class="dg-i"><div class="dg-l">Amount</div><div class="dg-v"><?= $r['amount']>0?'৳'.number_format($r['amount'],2):'Free' ?></div></div>
                <div class="dg-i"><div class="dg-l">Commission</div><div class="dg-v" style="color:#276749"><?= $r['commission']>0?'+৳'.number_format($r['commission'],2):'—' ?></div></div>
                <div class="dg-i"><div class="dg-l">Date</div><div class="dg-v"><?= date('d M, h:i',strtotime($r['created_at'])) ?></div></div>
            </div>
            <div style="background:white;border-radius:8px;padding:10px 12px;font-size:12px;color:#555;margin-bottom:10px;border:1px solid #f0f0f0;line-height:1.6"><b>Details:</b> <?= htmlspecialchars($r['details']) ?></div>
            <?php if($r['admin_note']): ?><div style="background:#fffbeb;border-radius:8px;padding:10px 12px;font-size:12px;color:#744210;margin-bottom:10px"><b>Note:</b> <?= htmlspecialchars($r['admin_note']) ?></div><?php endif; ?>
            <?php if(in_array($r['status'],['pending','processing'])): ?>
            <form method="POST" action="?view=requests&status=<?= $statusFilter ?>">
                <input type="hidden" name="req_id" value="<?= $r['id'] ?>">
                <input type="hidden" name="action" id="act<?= $r['id'] ?>">
                <input type="text" class="note-in" name="admin_note" placeholder="Note...">
                <div style="margin-bottom:10px"><input type="number" step="0.01" name="commission" placeholder="Commission ৳ (blank=auto)" style="width:200px;padding:8px 12px;border:2px solid #e8ecf4;border-radius:9px;font-size:13px;outline:none"></div>
                <div class="act-row">
                    <?php if($r['status']==='pending'): ?><button type="submit" class="btn btn-proc" onclick="document.getElementById('act<?= $r['id'] ?>').value='processing'"><i class="fas fa-clock"></i> Processing</button><?php endif; ?>
                    <button type="submit" class="btn btn-ok" onclick="document.getElementById('act<?= $r['id'] ?>').value='approve'"><i class="fas fa-check"></i> ✅ Approve</button>
                    <button type="submit" class="btn btn-fail" onclick="document.getElementById('act<?= $r['id'] ?>').value='reject'"><i class="fas fa-times"></i> ❌ Reject</button>
                </div>
            </form>
            <?php endif; ?>
        </div>
    </div>
    <?php endforeach; endif; ?>
    </div>
</div>
<?php endif; ?>

</div></div>

<!-- Category Modal -->
<div class="modal-bg" id="catModal">
<div class="modal-box">
    <div class="modal-title"><span id="catMT">Add Category</span><button class="close-btn" onclick="closeM('catModal')">✕</button></div>
    <form method="POST" enctype="multipart/form-data">
        <input type="hidden" name="action" value="save_cat">
        <input type="hidden" name="cat_id" id="catId">
        <input type="hidden" name="existing_cat_logo" id="catExistingLogo">
        <!-- Logo preview -->
        <div style="display:flex;align-items:center;gap:14px;margin-bottom:14px;padding:12px 14px;background:#f8fafc;border-radius:12px;border:1px solid #f0f0f0">
            <div id="catLogoPreview" style="width:56px;height:56px;border-radius:14px;background:#f0f4ff;display:flex;align-items:center;justify-content:center;font-size:28px;overflow:hidden;flex-shrink:0">📦</div>
            <div style="flex:1">
                <div style="font-size:12px;font-weight:700;color:#555;margin-bottom:6px">Category Photo</div>
                <label style="display:inline-flex;align-items:center;gap:6px;padding:7px 14px;background:var(--primary);color:white;border-radius:8px;font-size:12px;font-weight:700;cursor:pointer">
                    <i class="fas fa-upload"></i> Upload Photo
                    <input type="file" name="cat_logo" id="catLogoInput" accept="image/*" style="display:none" onchange="previewLogo(this,'catLogoPreview')">
                </label>
                <div style="font-size:10px;color:#aaa;margin-top:4px">JPG, PNG, SVG, WebP</div>
            </div>
        </div>
        <div class="frow2">
            <div class="fg"><label>Name *</label><input name="name" id="catName" required placeholder="Data Pack"></div>
            <div class="fg"><label>Emoji Icon</label><input name="icon" id="catIcon" value="📦"></div>
        </div>
        <div class="frow3">
            <div class="fg"><label>Color</label><input type="color" name="color" id="catColor" value="#1a3c8f" style="height:42px;padding:4px"></div>
            <div class="fg"><label>Sort</label><input type="number" name="sort_order" id="catSort" value="0"></div>
            <div class="fg"><label>Status</label><select name="is_active" id="catActive"><option value="1">✅ Active</option><option value="0">❌ Inactive</option></select></div>
        </div>
        <div class="modal-footer">
            <button type="button" id="delCatInlineBtn" class="btn btn-fail" style="display:none;margin-right:auto" onclick="submitDelCat()"><i class="fas fa-trash"></i> Delete</button>
            <button type="button" class="btn" style="background:#f5f5f5;color:#555" onclick="closeM('catModal')">Cancel</button>
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save</button>
        </div>
    </form>
    <form method="POST" id="delCatInlineForm" style="display:none">
        <input type="hidden" name="action" value="delete_cat">
        <input type="hidden" name="cat_id" id="delCatInlineId">
    </form>
</div>
</div>

<!-- Operator Modal -->
<div class="modal-bg" id="opModal">
<div class="modal-box">
    <div class="modal-title"><span id="opMT">Add Operator</span><button class="close-btn" onclick="closeM('opModal')">✕</button></div>
    <form method="POST" enctype="multipart/form-data">
        <input type="hidden" name="action" value="save_op">
        <input type="hidden" name="op_id" id="opId">
        <input type="hidden" name="existing_logo" id="opExistingLogo">
        <!-- Logo preview -->
        <div style="display:flex;align-items:center;gap:14px;margin-bottom:14px;padding:12px 14px;background:#f8fafc;border-radius:12px;border:1px solid #f0f0f0">
            <div id="opLogoPreview" style="width:56px;height:56px;border-radius:14px;background:#f0f4ff;display:flex;align-items:center;justify-content:center;font-size:28px;overflow:hidden;flex-shrink:0">📡</div>
            <div style="flex:1">
                <div style="font-size:12px;font-weight:700;color:#555;margin-bottom:6px">Operator Logo</div>
                <label style="display:inline-flex;align-items:center;gap:6px;padding:7px 14px;background:var(--primary);color:white;border-radius:8px;font-size:12px;font-weight:700;cursor:pointer">
                    <i class="fas fa-upload"></i> Upload Photo
                    <input type="file" name="op_logo" id="opLogoInput" accept="image/*" style="display:none" onchange="previewLogo(this,'opLogoPreview')">
                </label>
                <div style="font-size:10px;color:#aaa;margin-top:4px">JPG, PNG, SVG, WebP</div>
            </div>
        </div>
        <div class="frow2">
            <div class="fg"><label>Name *</label><input name="op_name" id="opName" required placeholder="Grameenphone"></div>
            <div class="fg"><label>Code *</label><input name="op_code" id="opCode" required placeholder="GP"></div>
        </div>
        <div class="frow3">
            <div class="fg"><label>Emoji Icon</label><input name="op_icon" id="opIcon" value="📡"></div>
            <div class="fg"><label>Color</label><input type="color" name="op_color" id="opColor" value="#1a3c8f" style="height:42px;padding:4px"></div>
            <div class="fg"><label>Sort</label><input type="number" name="op_sort" id="opSort" value="0"></div>
        </div>
        <div class="fg"><label>Status</label><select name="op_active" id="opActive"><option value="1">✅ Active</option><option value="0">❌ Inactive</option></select></div>
        <div class="modal-footer">
            <button type="button" id="delOpBtn" class="btn btn-fail" style="display:none;margin-right:auto" onclick="delOp()"><i class="fas fa-trash"></i> Delete</button>
            <button type="button" class="btn" style="background:#f5f5f5;color:#555" onclick="closeM('opModal')">Cancel</button>
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save</button>
        </div>
    </form>
    <form method="POST" id="delOpForm" style="display:none">
        <input type="hidden" name="action" value="delete_op">
        <input type="hidden" name="op_id" id="delOpId">
        <input type="hidden" name="cat_id_ctx" value="<?= $catId ?>">
    </form>
</div>
</div>

<!-- Package Modal -->
<div class="modal-bg" id="pkgModal">
<div class="modal-box">
    <div class="modal-title"><span id="pkgMT">Add Package</span><button class="close-btn" onclick="closeM('pkgModal')">✕</button></div>
    <form method="POST">
        <input type="hidden" name="action" value="save_pkg">
        <input type="hidden" name="pkg_id" id="pkgId">
        <input type="hidden" name="pkg_cat_id" value="<?= $catId ?>">
        <input type="hidden" name="pkg_op_id" value="<?= $opId ?>">
        <div class="fg"><label>Package Name *</label><input name="pkg_name" id="pkgName" required placeholder="10GB 30 Days"></div>
        <div class="fg"><label>Description</label><input name="pkg_desc" id="pkgDesc" placeholder="Social Pack, HD Video..."></div>
        <div class="sep">💰 Pricing & Commission</div>
        <div class="frow2">
            <div class="fg"><label>Price (৳) <span style="color:#aaa;font-size:10px">balance কাটবে</span></label><input type="number" step="0.01" name="pkg_price" id="pkgPrice" value="0"></div>
            <div class="fg"><label>Commission (৳) <span style="color:#38a169;font-size:10px">user পাবে</span></label><input type="number" step="0.01" name="pkg_commission" id="pkgComm" value="0"></div>
        </div>
        <div class="frow2">
            <div class="fg"><label>Sort</label><input type="number" name="pkg_sort" id="pkgSort" value="0"></div>
            <div class="fg"><label>Status</label><select name="pkg_active" id="pkgActive"><option value="1">✅ Active</option><option value="0">❌ Inactive</option></select></div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn" style="background:#f5f5f5;color:#555" onclick="closeM('pkgModal')">Cancel</button>
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save Package</button>
        </div>
    </form>
</div>
</div>

<!-- Bulk form -->
<form method="POST" id="bulkF" style="display:none">
    <input type="hidden" name="action" value="bulk_pkg">
    <input type="hidden" name="bulk_action" id="bAct">
    <div id="bIds"></div>
</form>

<script>
function openM(id){document.getElementById(id).classList.add('show');}
function closeM(id){document.getElementById(id).classList.remove('show');}
['catModal','opModal','pkgModal'].forEach(id=>document.getElementById(id)?.addEventListener('click',e=>{if(e.target===document.getElementById(id))closeM(id);}));

// Category
document.getElementById('addCatBtn')?.addEventListener('click',()=>{
    document.getElementById('catMT').textContent='Add Category';
    document.getElementById('catId').value=''; document.getElementById('catName').value='';
    document.getElementById('catIcon').value='📦'; document.getElementById('catColor').value='#1a3c8f';
    document.getElementById('catSort').value='0'; document.getElementById('catActive').value='1';
    document.getElementById('catExistingLogo').value='';
    document.getElementById('catLogoPreview').innerHTML='📦';
    document.getElementById('catLogoPreview').style.fontSize='28px';
    document.getElementById('catLogoInput').value='';
    document.getElementById('delCatInlineBtn').style.display='none';
    openM('catModal');
});
function openCatM(c){
    document.getElementById('catMT').textContent='Edit Category';
    document.getElementById('catId').value=c.id; document.getElementById('catName').value=c.name;
    document.getElementById('catIcon').value=c.icon; document.getElementById('catColor').value=c.color;
    document.getElementById('catSort').value=c.sort_order; document.getElementById('catActive').value=c.is_active;
    document.getElementById('catExistingLogo').value=c.logo||'';
    document.getElementById('catLogoInput').value='';
    const prev = document.getElementById('catLogoPreview');
    if(c.logo) { prev.innerHTML=`<img src="<?= SITE_URL ?>/${c.logo}" style="width:100%;height:100%;object-fit:contain;border-radius:12px">`; }
    else { prev.innerHTML=c.icon||'📦'; prev.style.fontSize='28px'; }
    document.getElementById('delCatInlineBtn').style.display='flex';
    document.getElementById('delCatInlineId').value=c.id;
    openM('catModal');
}
function submitDelCat(){if(confirm('Delete category and all packages?'))document.getElementById('delCatInlineForm').submit();}

// Operator
document.getElementById('addOpBtn')?.addEventListener('click',()=>{
    document.getElementById('opMT').textContent='Add Operator';
    ['opId','opName','opCode'].forEach(i=>document.getElementById(i).value='');
    document.getElementById('opIcon').value='📡'; document.getElementById('opColor').value='#1a3c8f';
    document.getElementById('opSort').value='0'; document.getElementById('opActive').value='1';
    document.getElementById('delOpBtn').style.display='none'; openM('opModal');
});
function openOpM(o){
    document.getElementById('opMT').textContent='Edit Operator';
    document.getElementById('opId').value=o.id; document.getElementById('opName').value=o.name;
    document.getElementById('opCode').value=o.code; document.getElementById('opIcon').value=o.icon;
    document.getElementById('opColor').value=o.color; document.getElementById('opSort').value=o.sort_order;
    document.getElementById('opActive').value=o.is_active;
    document.getElementById('opExistingLogo').value=o.logo||'';
    // Logo preview
    const prev = document.getElementById('opLogoPreview');
    if(o.logo) { prev.innerHTML=`<img src="<?= SITE_URL ?>/${o.logo}" style="width:100%;height:100%;object-fit:contain;border-radius:12px">`; }
    else { prev.textContent=o.icon||'📡'; prev.style.fontSize='28px'; }
    document.getElementById('delOpBtn').style.display='flex';
    document.getElementById('delOpId').value=o.id;
    openM('opModal');
}

function previewLogo(input, previewId) {
    if(!input.files || !input.files[0]) return;
    const reader = new FileReader();
    reader.onload = e => {
        const prev = document.getElementById(previewId);
        prev.innerHTML = `<img src="${e.target.result}" style="width:100%;height:100%;object-fit:contain;border-radius:12px">`;
    };
    reader.readAsDataURL(input.files[0]);
}
function delOp(){if(confirm('Delete operator and its packages?'))document.getElementById('delOpForm').submit();}

// Package
document.getElementById('addPkgBtn')?.addEventListener('click',()=>{
    document.getElementById('pkgMT').textContent='Add Package';
    ['pkgId','pkgName','pkgDesc'].forEach(i=>document.getElementById(i).value='');
    document.getElementById('pkgPrice').value='0'; document.getElementById('pkgComm').value='0';
    document.getElementById('pkgSort').value='0'; document.getElementById('pkgActive').value='1';
    openM('pkgModal');
});
function openPkgM(p){
    document.getElementById('pkgMT').textContent='Edit Package';
    document.getElementById('pkgId').value=p.id; document.getElementById('pkgName').value=p.name;
    document.getElementById('pkgDesc').value=p.description||''; document.getElementById('pkgPrice').value=p.price;
    document.getElementById('pkgComm').value=p.commission; document.getElementById('pkgSort').value=p.sort_order;
    document.getElementById('pkgActive').value=p.is_active;
    openM('pkgModal');
}

// Bulk packages
function updBulk(){const n=document.querySelectorAll('.pkg-cb:checked').length;document.getElementById('pkgBulkCnt').textContent=n+' selected';document.getElementById('pkgBulk').classList.toggle('show',n>0);}
function tAll(v){document.querySelectorAll('.pkg-cb').forEach(cb=>cb.checked=v);updBulk();}
function clearSel(){document.querySelectorAll('.pkg-cb').forEach(cb=>cb.checked=false);document.getElementById('saAll').checked=false;updBulk();}
function doBulk(a){
    const ids=[...document.querySelectorAll('.pkg-cb:checked')].map(cb=>cb.value);
    if(!ids.length)return;
    if(a==='delete'&&!confirm('Delete '+ids.length+' packages?'))return;
    document.getElementById('bAct').value=a;
    document.getElementById('bIds').innerHTML=ids.map(id=>`<input type="hidden" name="ids[]" value="${id}">`).join('');
    document.getElementById('bulkF').submit();
}

// Requests
function tR(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)':'';}
document.querySelectorAll('.req-card').forEach(card=>{
    if(card.querySelector('.s-pending,.s-processing')){const id=card.querySelector('[id^="rdet"]')?.id?.replace('rdet','');if(id){document.getElementById('rdet'+id)?.classList.add('open');const c=document.getElementById('rch'+id);if(c)c.style.transform='rotate(180deg)';}}
});
</script>
</body>
</html>
