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

// Upload dir
$uploadDir = '../assets/img/receipts/';
@mkdir($uploadDir, 0755, true);

// Create all tables safely
$tables = [
"CREATE TABLE IF NOT EXISTS bill_categories (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    icon VARCHAR(20) DEFAULT '🧾',
    logo VARCHAR(255) DEFAULT NULL,
    color VARCHAR(20) DEFAULT '#1a3c8f',
    commission DECIMAL(10,2) DEFAULT 0,
    is_active TINYINT(1) DEFAULT 1,
    sort_order INT DEFAULT 0
) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci",
"CREATE TABLE IF NOT EXISTS bill_providers (
    id INT AUTO_INCREMENT PRIMARY KEY,
    category_id INT NOT NULL,
    name VARCHAR(100) NOT NULL,
    code VARCHAR(20) DEFAULT '',
    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",
"CREATE TABLE IF NOT EXISTS bill_requests (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    category_id INT NOT NULL,
    provider_id INT DEFAULT NULL,
    bill_number VARCHAR(100) NOT NULL,
    bill_amount DECIMAL(10,2) NOT NULL DEFAULT 0,
    charge_amount DECIMAL(10,2) NOT NULL DEFAULT 0,
    mobile_number VARCHAR(20) DEFAULT NULL,
    bill_month VARCHAR(20) DEFAULT NULL,
    note TEXT DEFAULT NULL,
    reference VARCHAR(50) NOT NULL,
    status ENUM('pending','processing','success','failed') DEFAULT 'pending',
    commission DECIMAL(10,2) DEFAULT 0,
    balance_before DECIMAL(10,2) DEFAULT 0,
    balance_after DECIMAL(10,2) DEFAULT 0,
    admin_note TEXT DEFAULT NULL,
    receipt_image VARCHAR(255) DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci",
"CREATE TABLE IF NOT EXISTS bill_charge_slabs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    category_id INT NOT NULL,
    type ENUM('charge','commission') NOT NULL DEFAULT 'charge',
    amount_from DECIMAL(10,2) NOT NULL DEFAULT 0,
    amount_to DECIMAL(10,2) NOT NULL DEFAULT 99999,
    value DECIMAL(10,2) NOT NULL DEFAULT 0,
    value_type ENUM('fixed','percent') NOT NULL DEFAULT 'fixed',
    sort_order INT DEFAULT 0
) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
];
foreach($tables as $sql) { try { $db->exec($sql); } catch(Exception $e) {} }
try { $db->exec("ALTER TABLE bill_requests ADD COLUMN IF NOT EXISTS charge_amount DECIMAL(10,2) NOT NULL DEFAULT 0"); } catch(Exception $e) {}

// Default data
try {
    if($db->query("SELECT COUNT(*) FROM bill_categories")->fetchColumn()==0) {
        $db->exec("INSERT INTO bill_categories (name,icon,color,sort_order) VALUES
            ('Electricity','⚡','#f6e05e',1),('Gas','🔥','#fc8181',2),
            ('Water','💧','#63b3ed',3),('Internet','🌐','#68d391',4),('Telephone','📞','#b794f4',5)");
    }
    if($db->query("SELECT COUNT(*) FROM bill_providers")->fetchColumn()==0) {
        $db->exec("INSERT INTO bill_providers (category_id,name,code,icon,color,sort_order) VALUES
            (1,'DESCO','DESCO','⚡','#f6e05e',1),(1,'DPDC','DPDC','⚡','#f6ad55',2),(1,'BREB','BREB','⚡','#68d391',3),(1,'NESCO','NESCO','⚡','#63b3ed',4),
            (2,'Titas Gas','TITAS','🔥','#fc8181',1),(2,'Bakhrabad','BAKHR','🔥','#f6ad55',2),
            (3,'DWASA','DWASA','💧','#63b3ed',1),(3,'CWASA','CWASA','💧','#4299e1',2),
            (4,'ISP Bill','ISP','🌐','#68d391',1),(5,'BTCL','BTCL','📞','#b794f4',1)");
    }
} 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['cat_name']??'');
        $icon=sanitize($_POST['cat_icon']??'🧾');
        $color=sanitize($_POST['cat_color']??'#1a3c8f');
        $comm=floatval($_POST['cat_commission']??0);
        $sort=intval($_POST['cat_sort']??0);
        $active=intval($_POST['cat_active']??1);
        $logo=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'])) {
                $fn='bcat_'.time().'.'.$ext;
                if(move_uploaded_file($_FILES['cat_logo']['tmp_name'],$uploadDir.$fn)) $logo='assets/img/receipts/'.$fn;
            }
        }
        if($id) $db->prepare("UPDATE bill_categories SET name=?,icon=?,logo=?,color=?,commission=?,sort_order=?,is_active=? WHERE id=?")->execute([$name,$icon,$logo?:null,$color,$comm,$sort,$active,$id]);
        else    $db->prepare("INSERT INTO bill_categories (name,icon,logo,color,commission,sort_order,is_active) VALUES (?,?,?,?,?,?,?)")->execute([$name,$icon,$logo?:null,$color,$comm,$sort,$active]);
        header('Location: bill_pay.php?view=categories'); exit;
    }

    if ($action === 'delete_cat') {
        $id=intval($_POST['cat_id']);
        $db->prepare("DELETE FROM bill_providers WHERE category_id=?")->execute([$id]);
        $db->prepare("DELETE FROM bill_categories WHERE id=?")->execute([$id]);
        header('Location: bill_pay.php?view=categories'); exit;
    }

    if ($action === 'save_slab') {
        $id=intval($_POST['slab_id']??0);
        $catId=intval($_POST['slab_cat_id']??0);
        $type=sanitize($_POST['slab_type']??'charge');
        $from=floatval($_POST['slab_from']??0);
        $to=floatval($_POST['slab_to']??99999);
        $val=floatval($_POST['slab_value']??0);
        $vtype=sanitize($_POST['slab_vtype']??'fixed');
        $sort=intval($_POST['slab_sort']??0);
        if($id) $db->prepare("UPDATE bill_charge_slabs SET type=?,amount_from=?,amount_to=?,value=?,value_type=?,sort_order=? WHERE id=?")->execute([$type,$from,$to,$val,$vtype,$sort,$id]);
        else    $db->prepare("INSERT INTO bill_charge_slabs (category_id,type,amount_from,amount_to,value,value_type,sort_order) VALUES (?,?,?,?,?,?,?)")->execute([$catId,$type,$from,$to,$val,$vtype,$sort]);
        header("Location: bill_pay.php?view=categories&slabs=$catId"); exit;
    }

    if ($action === 'delete_slab') {
        $db->prepare("DELETE FROM bill_charge_slabs WHERE id=?")->execute([intval($_POST['slab_id'])]);
        header("Location: bill_pay.php?view=categories&slabs=".intval($_POST['slab_cat_id'])); exit;
    }

    if ($action === 'save_prov') {
        $id=intval($_POST['prov_id']??0);
        $catId=intval($_POST['prov_cat_id']??0);
        $name=sanitize($_POST['prov_name']??'');
        $code=sanitize($_POST['prov_code']??'');
        $icon=sanitize($_POST['prov_icon']??'🏢');
        $color=sanitize($_POST['prov_color']??'#1a3c8f');
        $sort=intval($_POST['prov_sort']??0);
        $active=intval($_POST['prov_active']??1);
        $logo=sanitize($_POST['existing_prov_logo']??'');
        if(!empty($_FILES['prov_logo']['name'])) {
            $ext=strtolower(pathinfo($_FILES['prov_logo']['name'],PATHINFO_EXTENSION));
            if(in_array($ext,['jpg','jpeg','png','svg','webp','gif'])) {
                $fn='bprov_'.time().'.'.$ext;
                if(move_uploaded_file($_FILES['prov_logo']['tmp_name'],$uploadDir.$fn)) $logo='assets/img/receipts/'.$fn;
            }
        }
        if($id) $db->prepare("UPDATE bill_providers SET category_id=?,name=?,code=?,icon=?,logo=?,color=?,sort_order=?,is_active=? WHERE id=?")->execute([$catId,$name,$code,$icon,$logo?:null,$color,$sort,$active,$id]);
        else    $db->prepare("INSERT INTO bill_providers (category_id,name,code,icon,logo,color,sort_order,is_active) VALUES (?,?,?,?,?,?,?,?)")->execute([$catId,$name,$code,$icon,$logo?:null,$color,$sort,$active]);
        header('Location: bill_pay.php?view=providers&cat='.$catId); exit;
    }

    if ($action === 'delete_prov') {
        $catId=intval($_POST['prov_cat_id']??0);
        $db->prepare("DELETE FROM bill_providers WHERE id=?")->execute([intval($_POST['prov_id'])]);
        header('Location: bill_pay.php?view=providers&cat='.$catId); exit;
    }

    if (in_array($action,['approve','reject','processing'])) {
        $id=intval($_POST['req_id']);
        $note=sanitize($_POST['admin_note']??'');
        $comm=floatval($_POST['commission']??0);
        try {
            $s=$db->prepare("SELECT r.*,u.name as uname,c.name as cat_name,c.icon as cat_icon FROM bill_requests r JOIN users u ON r.user_id=u.id JOIN bill_categories c ON r.category_id=c.id WHERE r.id=?");
            $s->execute([$id]); $req=$s->fetch();
        } catch(Exception $e) { $req=null; }

        if($req) {
            $receiptPath=$req['receipt_image']??'';
            if(!empty($_FILES['receipt']['name'])) {
                $ext=strtolower(pathinfo($_FILES['receipt']['name'],PATHINFO_EXTENSION));
                if(in_array($ext,['jpg','jpeg','png','gif','webp','pdf'])) {
                    $fn='receipt_'.$req['reference'].'.'.$ext;
                    if(move_uploaded_file($_FILES['receipt']['tmp_name'],$uploadDir.$fn)) $receiptPath='assets/img/receipts/'.$fn;
                }
            }
            $totalDeducted=floatval($req['bill_amount'])+floatval($req['charge_amount']??0);

            if($action==='approve') {
                $db->beginTransaction();
                try {
                    if($comm<=0) {
                        $sl=$db->prepare("SELECT * FROM bill_charge_slabs WHERE category_id=? AND type='commission' AND amount_from<=? AND amount_to>=? ORDER BY sort_order LIMIT 1");
                        $sl->execute([$req['category_id'],$req['bill_amount'],$req['bill_amount']]);
                        $sl=$sl->fetch();
                        if($sl) $comm=$sl['value_type']==='percent'?round($req['bill_amount']*$sl['value']/100,2):floatval($sl['value']);
                    }
                    $db->prepare("UPDATE bill_requests SET status='success',admin_note=?,commission=?,receipt_image=? WHERE id=?")->execute([$note,$comm,$receiptPath,$id]);
                    $db->prepare("UPDATE transactions SET status='success' WHERE reference=? AND type='bill'")->execute([$req['reference']]);
                    if($comm>0) {
                        $db->prepare("UPDATE users SET balance=balance+? WHERE id=?")->execute([$comm,$req['user_id']]);
                        $nb=floatval($db->query("SELECT balance FROM users WHERE id={$req['user_id']}")->fetchColumn());
                        $ref2='BLC'.strtoupper(substr(uniqid(),7));
                        $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,$ref2,'success','Bill Pay: '.$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'],'✅ Bill Pay Done!',$req['cat_icon'].' '.$req['cat_name'].' approved.']);
                    $db->commit();
                    $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 bill_requests SET status='failed',admin_note=?,receipt_image=? WHERE id=?")->execute([$note,$receiptPath,$id]);
                    $db->prepare("UPDATE transactions SET status='failed' WHERE reference=? AND type='bill'")->execute([$req['reference']]);
                    $db->prepare("UPDATE users SET balance=balance+? WHERE id=?")->execute([$totalDeducted,$req['user_id']]);
                    $nb=floatval($db->query("SELECT balance FROM users WHERE id={$req['user_id']}")->fetchColumn());
                    $ref2='BLR'.strtoupper(substr(uniqid(),7));
                    $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',$totalDeducted,$totalDeducted,$nb-$totalDeducted,$nb,$ref2,'success','Refund: '.$req['reference']]);
                    $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'error')")->execute([$req['user_id'],'❌ Bill Pay Rejected','৳'.number_format($totalDeducted,2).' refunded.']);
                    $db->commit();
                    $msg=['ok'=>true,'text'=>'Rejected & refunded ৳'.number_format($totalDeducted,2).'!'];
                } catch(Exception $e) { $db->rollBack(); $msg=['ok'=>false,'text'=>$e->getMessage()]; }

            } elseif($action==='processing') {
                try {
                    $db->prepare("UPDATE bill_requests SET status='processing',admin_note=?,receipt_image=? WHERE id=?")->execute([$note,$receiptPath,$id]);
                    $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'info')")->execute([$req['user_id'],'🔄 Processing','Your bill pay is being processed.']);
                    $msg=['ok'=>true,'text'=>'Set to Processing!'];
                } catch(Exception $e) { $msg=['ok'=>false,'text'=>$e->getMessage()]; }
            }
        }
    }
}

$view = $_GET['view'] ?? 'requests';
$catId = intval($_GET['cat'] ?? 0);
$statusFilter = $_GET['status'] ?? 'pending';
$slabsCatId = intval($_GET['slabs'] ?? 0);

$categories=[]; $allSlabs=[]; $slabsMap=[]; $providers=[]; $requests=[]; $currentCat=null;
$counts=['pending'=>0,'processing'=>0,'success'=>0,'failed'=>0];

try { $categories=$db->query("SELECT c.*,(SELECT COUNT(*) FROM bill_providers WHERE category_id=c.id) as prov_count FROM bill_categories c ORDER BY c.sort_order,c.id")->fetchAll(); } catch(Exception $e) {}
try { $allSlabs=$db->query("SELECT * FROM bill_charge_slabs ORDER BY category_id,type,sort_order,amount_from")->fetchAll(); } catch(Exception $e) {}
foreach($allSlabs as $sl) $slabsMap[$sl['category_id']][]=$sl;
try { if($catId){ $s=$db->prepare("SELECT * FROM bill_categories WHERE id=?");$s->execute([$catId]);$currentCat=$s->fetch();} } catch(Exception $e) {}
try { if($view==='providers'&&$catId){ $s=$db->prepare("SELECT * FROM bill_providers WHERE category_id=? ORDER BY sort_order,id");$s->execute([$catId]);$providers=$s->fetchAll();} } catch(Exception $e) {}
try {
    $rWhere=$statusFilter!=='all'?"WHERE r.status=?":"WHERE 1=1";
    $rParams=$statusFilter!=='all'?[$statusFilter]:[];
    $s=$db->prepare("SELECT r.*,u.name as uname,u.phone as uphone,c.name as cat_name,c.icon as cat_icon,p.name as prov_name FROM bill_requests r JOIN users u ON r.user_id=u.id JOIN bill_categories c ON r.category_id=c.id LEFT JOIN bill_providers p ON r.provider_id=p.id $rWhere ORDER BY r.created_at DESC LIMIT 100");
    $s->execute($rParams); $requests=$s->fetchAll();
} catch(Exception $e) {}
try {
    $counts['pending']   =$db->query("SELECT COUNT(*) FROM bill_requests WHERE status='pending'")->fetchColumn();
    $counts['processing']=$db->query("SELECT COUNT(*) FROM bill_requests WHERE status='processing'")->fetchColumn();
    $counts['success']   =$db->query("SELECT COUNT(*) FROM bill_requests WHERE status='success'")->fetchColumn();
    $counts['failed']    =$db->query("SELECT COUNT(*) FROM bill_requests WHERE status='failed'")->fetchColumn();
} catch(Exception $e) {}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Bill Pay — 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;text-decoration:none;transition:0.15s}
.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}
.bc{display:flex;align-items:center;gap:8px;font-size:13px;margin-bottom:14px;flex-wrap:wrap}
.bc a{color:var(--primary);text-decoration:none;font-weight:600}
.bc-sep{color:#ccc}.bc-cur{font-weight:700}
.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}
.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);transform:translateY(-1px)}
.cat-card-body{padding:18px 16px;cursor:pointer;text-decoration:none;display:block}
.cat-card-actions{border-top:1px solid #f5f5f5;padding:8px 14px;display:flex;gap:8px;background:#fafbfc;flex-wrap:wrap}
.prov-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:10px}
.prov-card{background:white;border-radius:12px;border:2px solid #f0f0f0;overflow:hidden;transition:0.2s}
.prov-card:hover{border-color:var(--primary);transform:translateY(-1px)}
.prov-card-body{padding:14px;text-align:center}
.prov-card-actions{border-top:1px solid #f5f5f5;padding:8px 12px;display:flex;gap:6px;background:#fafbfc}
.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;font-weight:600}
.dg-v{font-size:12px;font-weight:700;color:#333}
.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}
.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;align-items:center}
.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.2s;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.2s}
.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}
.upload-area{border:2px dashed #e8ecf4;border-radius:12px;padding:14px;text-align:center;cursor:pointer;position:relative;transition:0.2s}
.upload-area:hover{border-color:var(--primary);background:#f0f4ff}
.upload-area input{position:absolute;inset:0;opacity:0;cursor:pointer;width:100%;height:100%}
.receipt-preview{width:100%;border-radius:10px;margin-top:8px;display:none}
.slab-table{width:100%;border-collapse:collapse;font-size:13px}
.slab-table th{padding:10px 14px;background:#f8fafc;text-align:left;font-weight:700;color:#888;font-size:11px;text-transform:uppercase;border-bottom:2px solid #f0f0f0}
.slab-table td{padding:11px 14px;border-bottom:1px solid #f5f5f5;vertical-align:middle}
.slab-table tr:last-child td{border:none}
.slab-table tr:hover td{background:#fafbff}
.slab-panel{display:none;margin-top:14px;background:white;border-radius:14px;border:2px solid #f0f0f0;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.06)}
.slab-panel.open{display:block}
.slab-panel-head{padding:14px 18px;background:linear-gradient(135deg,#f8fafc,#f0f4ff);border-bottom:2px solid #f0f0f0;display:flex;align-items:center;justify-content:space-between}
</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">🧾 Bill Pay</span>
    </div>
    <div class="topbar-right">
        <?php if($view==='categories'): ?>
        <button class="btn btn-primary btn-sm" onclick="openM('catModal')"><i class="fas fa-plus"></i> Category</button>
        <?php endif; ?>
        <?php if($view==='providers'&&$catId): ?>
        <button class="btn btn-primary btn-sm" onclick="openProvM()"><i class="fas fa-plus"></i> Provider</button>
        <?php endif; ?>
        <a href="?view=requests" class="btn btn-sm" style="background:#fffbeb;color:#d69e2e"><i class="fas fa-inbox"></i> Requests (<?= $counts['pending'] ?>)</a>
        <a href="?view=categories" class="btn btn-sm" style="background:#f0f4ff;color:var(--primary)"><i class="fas fa-th-large"></i> Categories</a>
    </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 -->
<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 [$em,$lb,$cnt,$bg,$cl]): ?>
<div style="background:<?= $bg ?>;border-radius:12px;padding:14px;text-align:center;cursor:pointer" onclick="location.href='?view=requests&status=<?= strtolower($lb) ?>'">
    <div style="font-size:22px;font-weight:800;color:<?= $cl ?>"><?= $cnt ?></div>
    <div style="font-size:11px;color:<?= $cl ?>;opacity:0.8"><?= $em ?> <?= $lb ?></div>
</div>
<?php endforeach; ?>
</div>

<!-- Breadcrumb -->
<div class="bc">
    <a href="?view=categories">🗂 Categories</a>
    <?php if($view==='providers'&&$currentCat): ?>
    <span class="bc-sep">›</span><span class="bc-cur"><?= $currentCat['icon'] ?> <?= htmlspecialchars($currentCat['name']) ?></span>
    <?php elseif($view==='requests'): ?>
    <span class="bc-sep">›</span><span class="bc-cur">📋 Requests</span>
    <?php endif; ?>
</div>

<?php if($view==='categories'): ?>
<!-- CATEGORIES -->
<div class="card">
    <div class="card-h"><span>📂 Bill Categories</span><small style="color:#aaa"><?= count($categories) ?> total</small></div>
    <div class="card-b">
    <?php if(empty($categories)): ?>
    <div style="text-align:center;padding:30px;color:#ccc">No categories. Click + Category</div>
    <?php else: ?>
    <div class="cat-grid">
    <?php foreach($categories as $c):
        $catSlabs=$slabsMap[$c['id']]??[];
        $chargeSlabs=array_filter($catSlabs,fn($s)=>$s['type']==='charge');
        $commSlabs=array_filter($catSlabs,fn($s)=>$s['type']==='commission');
    ?>
    <div class="cat-card">
        <a href="?view=providers&cat=<?= $c['id'] ?>" class="cat-card-body" style="text-decoration:none">
            <?php if($c['logo']): ?>
            <img src="<?= SITE_URL ?>/<?= htmlspecialchars($c['logo']) ?>" style="width:48px;height:48px;border-radius:12px;object-fit:contain;background:<?= $c['color'] ?>18;padding:6px;margin-bottom:8px;display:block">
            <?php else: ?>
            <div style="font-size:32px;margin-bottom:8px"><?= $c['icon'] ?></div>
            <?php endif; ?>
            <div style="font-size:13px;font-weight:800;color:#1a1a2e;margin-bottom:3px"><?= htmlspecialchars($c['name']) ?></div>
            <div style="font-size:11px;color:#aaa;margin-bottom:6px"><?= $c['prov_count'] ?> providers</div>
            <div style="display:flex;gap:4px;flex-wrap:wrap">
                <?php if(count($chargeSlabs)>0): ?><span style="font-size:10px;background:#fff5f5;color:#e53e3e;padding:2px 7px;border-radius:10px;font-weight:700">💳 <?= count($chargeSlabs) ?></span><?php endif; ?>
                <?php if(count($commSlabs)>0): ?><span style="font-size:10px;background:#f0fff4;color:#276749;padding:2px 7px;border-radius:10px;font-weight:700">💸 <?= count($commSlabs) ?></span><?php endif; ?>
            </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="font-size:11px"></i> Edit</button>
            <button class="btn-sm" style="background:#f0fff4;color:#276749" onclick="toggleSlabs(<?= $c['id'] ?>,'<?= htmlspecialchars($c['name'],ENT_QUOTES) ?>')"><i class="fas fa-layer-group" style="font-size:11px"></i> Slabs</button>
            <form method="POST" onsubmit="return confirm('Delete?')" style="display:inline">
                <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>

    <!-- Slab panels — full width, outside grid -->
    <?php foreach($categories as $c):
        $catSlabs=$slabsMap[$c['id']]??[];
    ?>
    <div class="slab-panel <?= $slabsCatId==$c['id']?'open':'' ?>" id="slabs<?= $c['id'] ?>">
        <div class="slab-panel-head">
            <div>
                <div style="font-size:14px;font-weight:800;color:#1a1a2e"><?= $c['icon'] ?> <?= htmlspecialchars($c['name']) ?> — Charge & Commission Slabs</div>
                <div style="font-size:11px;color:#aaa;margin-top:2px">Range based charge/commission for bill amounts</div>
            </div>
            <div style="display:flex;gap:8px;align-items:center">
                <button class="btn btn-primary btn-sm" onclick="openSlabM(<?= $c['id'] ?>)"><i class="fas fa-plus"></i> Add Slab</button>
                <button onclick="toggleSlabs(<?= $c['id'] ?>,'<?= htmlspecialchars($c['name'],ENT_QUOTES) ?>')" style="background:#f5f5f5;border:none;width:30px;height:30px;border-radius:50%;cursor:pointer;font-size:14px;color:#888">✕</button>
            </div>
        </div>
        <?php if(empty($catSlabs)): ?>
        <div style="text-align:center;padding:30px;color:#ccc">
            <i class="fas fa-layer-group" style="font-size:28px;display:block;margin-bottom:8px;color:#ddd"></i>
            No slabs yet. Click <b>+ Add Slab</b> to set charge/commission ranges.
        </div>
        <?php else: ?>
        <div style="overflow-x:auto">
        <table class="slab-table">
            <thead>
                <tr><th>Type</th><th>Bill Amount Range</th><th>Value</th><th>Value Type</th><th style="text-align:right">Action</th></tr>
            </thead>
            <tbody>
            <?php foreach($catSlabs as $sl): ?>
            <tr>
                <td>
                    <span style="font-size:12px;font-weight:700;padding:4px 12px;border-radius:20px;background:<?= $sl['type']==='charge'?'#fff5f5':'#f0fff4' ?>;color:<?= $sl['type']==='charge'?'#e53e3e':'#276749' ?>">
                        <?= $sl['type']==='charge'?'💳 Charge':'💸 Commission' ?>
                    </span>
                </td>
                <td style="font-family:monospace;font-weight:600">
                    ৳<?= number_format($sl['amount_from'],0) ?> 
                    <span style="color:#aaa">—</span> 
                    <?= $sl['amount_to']>=99999?'<span style="color:#aaa">Unlimited</span>':'৳'.number_format($sl['amount_to'],0) ?>
                </td>
                <td style="font-size:15px;font-weight:800;color:<?= $sl['type']==='charge'?'#e53e3e':'#276749' ?>">
                    <?= $sl['value_type']==='percent'?$sl['value'].'%':'৳'.number_format($sl['value'],2) ?>
                </td>
                <td><span style="font-size:11px;background:#f8fafc;padding:3px 8px;border-radius:8px;color:#888;font-weight:600"><?= $sl['value_type']==='percent'?'Percentage':'Fixed Amount' ?></span></td>
                <td style="text-align:right">
                    <button class="btn-sm" style="background:#ebf8ff;color:var(--primary)" onclick='openSlabMEdit(<?= htmlspecialchars(json_encode($sl),ENT_QUOTES) ?>)'><i class="fas fa-edit"></i> Edit</button>
                    <form method="POST" style="display:inline" onsubmit="return confirm('Delete this slab?')">
                        <input type="hidden" name="action" value="delete_slab">
                        <input type="hidden" name="slab_id" value="<?= $sl['id'] ?>">
                        <input type="hidden" name="slab_cat_id" value="<?= $c['id'] ?>">
                        <button type="submit" class="btn-sm" style="background:#fff5f5;color:#e53e3e"><i class="fas fa-trash"></i> Delete</button>
                    </form>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        </div>
        <?php endif; ?>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
    </div>
</div>

<?php elseif($view==='providers'&&$currentCat): ?>
<!-- PROVIDERS -->
<div class="card">
    <div class="card-h"><span><?= $currentCat['icon'] ?> <?= htmlspecialchars($currentCat['name']) ?> — Providers</span></div>
    <div class="card-b">
    <?php if(empty($providers)): ?>
    <div style="text-align:center;padding:30px;color:#ccc">No providers. Click + Provider</div>
    <?php else: ?>
    <div class="prov-grid">
    <?php foreach($providers as $p): ?>
    <div class="prov-card">
        <div class="prov-card-body">
            <?php if($p['logo']): ?>
            <img src="<?= SITE_URL ?>/<?= htmlspecialchars($p['logo']) ?>" style="width:46px;height:46px;border-radius:10px;object-fit:contain;background:<?= $p['color'] ?>18;padding:5px;display:block;margin:0 auto 8px">
            <?php else: ?>
            <div style="font-size:26px;margin-bottom:8px"><?= $p['icon'] ?></div>
            <?php endif; ?>
            <div style="font-size:13px;font-weight:800;color:#1a1a2e;margin-bottom:4px"><?= htmlspecialchars($p['name']) ?></div>
            <div style="font-size:10px;background:<?= $p['color'] ?>;color:white;display:inline-block;padding:2px 8px;border-radius:20px;font-weight:700"><?= htmlspecialchars($p['code']?:$p['name']) ?></div>
        </div>
        <div class="prov-card-actions">
            <button class="btn-sm" style="background:#ebf8ff;color:var(--primary)" onclick='openEditProvM(<?= htmlspecialchars(json_encode($p),ENT_QUOTES) ?>)'><i class="fas fa-edit" style="font-size:11px"></i></button>
            <form method="POST" onsubmit="return confirm('Delete?')" style="display:inline">
                <input type="hidden" name="action" value="delete_prov"><input type="hidden" name="prov_id" value="<?= $p['id'] ?>"><input type="hidden" name="prov_cat_id" value="<?= $catId ?>">
                <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==='requests'): ?>
<!-- REQUESTS -->
<div class="card">
    <div class="card-h">📋 Bill Pay Requests</div>
    <div style="padding:10px 16px;border-bottom:1px solid #f5f5f5;display:flex;gap:6px;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):
        $totalPaid=floatval($r['bill_amount'])+floatval($r['charge_amount']??0);
    ?>
    <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['cat_name']) ?><?= $r['prov_name']?' — '.htmlspecialchars($r['prov_name']):'' ?></div>
                <div style="font-size:11px;color:#aaa">👤 <?= htmlspecialchars($r['uname']) ?> · <?= 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:#e53e3e">৳<?= number_format($totalPaid,2) ?></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">Bill No</div><div class="dg-v" style="font-family:monospace"><?= htmlspecialchars($r['bill_number']) ?></div></div>
                <div class="dg-i"><div class="dg-l">Bill Amount</div><div class="dg-v" style="color:#e53e3e">৳<?= number_format($r['bill_amount'],2) ?></div></div>
                <?php if(floatval($r['charge_amount']??0)>0): ?><div class="dg-i"><div class="dg-l">Charge</div><div class="dg-v" style="color:#e53e3e">৳<?= number_format($r['charge_amount'],2) ?></div></div><?php endif; ?>
                <div class="dg-i"><div class="dg-l">Mobile</div><div class="dg-v"><?= $r['mobile_number']??'—' ?></div></div>
                <div class="dg-i"><div class="dg-l">Month</div><div class="dg-v"><?= htmlspecialchars($r['bill_month']??'—') ?></div></div>
                <div class="dg-i"><div class="dg-l">Reference</div><div class="dg-v" style="font-size:11px;font-family:monospace"><?= $r['reference'] ?></div></div>
                <?php if($r['commission']>0): ?><div class="dg-i"><div class="dg-l">Commission</div><div class="dg-v" style="color:#276749">+৳<?= number_format($r['commission'],2) ?></div></div><?php endif; ?>
            </div>
            <?php if($r['note']): ?><div style="background:white;border-radius:8px;padding:10px 12px;font-size:12px;color:#555;margin-bottom:10px;border:1px solid #f0f0f0"><?= htmlspecialchars($r['note']) ?></div><?php endif; ?>
            <?php if($r['admin_note']): ?><div style="background:#fffbeb;border-radius:8px;padding:10px 12px;font-size:12px;color:#744210;margin-bottom:10px;border-left:3px solid #d69e2e"><?= htmlspecialchars($r['admin_note']) ?></div><?php endif; ?>
            <?php if($r['receipt_image']): ?>
            <div style="margin-bottom:10px"><a href="<?= SITE_URL ?>/<?= htmlspecialchars($r['receipt_image']) ?>" target="_blank"><img src="<?= SITE_URL ?>/<?= htmlspecialchars($r['receipt_image']) ?>" style="max-width:200px;border-radius:10px;border:2px solid #f0f0f0"></a></div>
            <?php endif; ?>
            <?php if(in_array($r['status'],['pending','processing'])): ?>
            <form method="POST" action="?view=requests&status=<?= $statusFilter ?>" enctype="multipart/form-data">
                <input type="hidden" name="req_id" value="<?= $r['id'] ?>">
                <input type="hidden" name="action" id="act<?= $r['id'] ?>">
                <textarea class="note-in" name="admin_note" placeholder="Admin note..." rows="2"></textarea>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:8px">
                    <input type="number" step="0.01" name="commission" placeholder="Commission ৳ (blank=auto)" style="padding:9px 12px;border:2px solid #e8ecf4;border-radius:9px;font-size:13px;outline:none">
                    <div class="upload-area">
                        <input type="file" name="receipt" accept="image/*,application/pdf" onchange="previewReceipt(this,<?= $r['id'] ?>)">
                        <i class="fas fa-camera" style="font-size:16px;color:#aaa;display:block;margin-bottom:4px"></i>
                        <span style="font-size:11px;color:#aaa">Upload Receipt</span>
                    </div>
                </div>
                <img id="rpreview<?= $r['id'] ?>" class="receipt-preview">
                <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" value="">
        <input type="hidden" name="existing_cat_logo" id="catExLogo" value="">
        <div style="display:flex;align-items:center;gap:14px;padding:12px;background:#f8fafc;border-radius:12px;margin-bottom:14px">
            <div id="catLogoPreview" style="width:52px;height:52px;border-radius:12px;background:#f0f4ff;display:flex;align-items:center;justify-content:center;font-size:26px;overflow:hidden;flex-shrink:0">🧾</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" accept="image/*" style="display:none" onchange="previewLogo(this,'catLogoPreview')">
            </label>
        </div>
        <div class="frow2">
            <div class="fg"><label>Name *</label><input name="cat_name" id="catName" required placeholder="Electricity"></div>
            <div class="fg"><label>Emoji Icon</label><input name="cat_icon" id="catIcon" value="🧾"></div>
        </div>
        <div class="frow2">
            <div class="fg"><label>Commission %</label><input type="number" step="0.01" name="cat_commission" id="catComm" value="0"></div>
            <div class="fg"><label>Color</label><input type="color" name="cat_color" id="catColor" value="#1a3c8f" style="height:42px;padding:4px"></div>
        </div>
        <div class="frow2">
            <div class="fg"><label>Sort</label><input type="number" name="cat_sort" id="catSort" value="0"></div>
            <div class="fg"><label>Status</label><select name="cat_active" id="catActive"><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('catModal')">Cancel</button>
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save</button>
        </div>
    </form>
</div>
</div>

<!-- Provider Modal -->
<div class="modal-bg" id="provModal">
<div class="modal-box">
    <div class="modal-title"><span id="provMT">Add Provider</span><button class="close-btn" onclick="closeM('provModal')">✕</button></div>
    <form method="POST" enctype="multipart/form-data">
        <input type="hidden" name="action" value="save_prov">
        <input type="hidden" name="prov_id" id="provId" value="">
        <input type="hidden" name="prov_cat_id" value="<?= $catId ?>">
        <input type="hidden" name="existing_prov_logo" id="provExLogo" value="">
        <div style="display:flex;align-items:center;gap:14px;padding:12px;background:#f8fafc;border-radius:12px;margin-bottom:14px">
            <div id="provLogoPreview" style="width:52px;height:52px;border-radius:12px;background:#f0f4ff;display:flex;align-items:center;justify-content:center;font-size:26px;overflow:hidden;flex-shrink:0">🏢</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 Logo
                <input type="file" name="prov_logo" accept="image/*" style="display:none" onchange="previewLogo(this,'provLogoPreview')">
            </label>
        </div>
        <div class="frow2">
            <div class="fg"><label>Name *</label><input name="prov_name" id="provName" required placeholder="DESCO"></div>
            <div class="fg"><label>Code</label><input name="prov_code" id="provCode" placeholder="DESCO"></div>
        </div>
        <div class="frow2">
            <div class="fg"><label>Emoji Icon</label><input name="prov_icon" id="provIcon" value="🏢"></div>
            <div class="fg"><label>Color</label><input type="color" name="prov_color" id="provColor" value="#1a3c8f" style="height:42px;padding:4px"></div>
        </div>
        <div class="frow2">
            <div class="fg"><label>Sort</label><input type="number" name="prov_sort" id="provSort" value="0"></div>
            <div class="fg"><label>Status</label><select name="prov_active" id="provActive"><option value="1">✅ Active</option><option value="0">❌ Inactive</option></select></div>
        </div>
        <div class="modal-footer">
            <button type="button" id="delProvBtn" class="btn btn-fail" style="display:none;margin-right:auto" onclick="delProv()"><i class="fas fa-trash"></i> Delete</button>
            <button type="button" class="btn" style="background:#f5f5f5;color:#555" onclick="closeM('provModal')">Cancel</button>
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save</button>
        </div>
    </form>
    <form method="POST" id="delProvForm" style="display:none">
        <input type="hidden" name="action" value="delete_prov">
        <input type="hidden" name="prov_id" id="delProvId">
        <input type="hidden" name="prov_cat_id" value="<?= $catId ?>">
    </form>
</div>
</div>

<!-- Slab Modal -->
<div class="modal-bg" id="slabModal">
<div class="modal-box">
    <div class="modal-title"><span id="slabMT">Add Slab</span><button class="close-btn" onclick="closeM('slabModal')">✕</button></div>
    <form method="POST">
        <input type="hidden" name="action" value="save_slab">
        <input type="hidden" name="slab_id" id="slabId" value="">
        <input type="hidden" name="slab_cat_id" id="slabCatId" value="">
        <div class="fg"><label>Type</label>
            <select name="slab_type" id="slabType">
                <option value="charge">💳 Charge (user pays extra)</option>
                <option value="commission">💸 Commission (user earns)</option>
            </select>
        </div>
        <div class="frow2">
            <div class="fg"><label>Amount From (৳)</label><input type="number" step="0.01" name="slab_from" id="slabFrom" required placeholder="0"></div>
            <div class="fg"><label>Amount To (৳)</label><input type="number" step="0.01" name="slab_to" id="slabTo" required placeholder="99999"><small style="font-size:10px;color:#aaa">99999 = unlimited</small></div>
        </div>
        <div class="frow2">
            <div class="fg"><label>Value</label><input type="number" step="0.01" name="slab_value" id="slabValue" required placeholder="0"></div>
            <div class="fg"><label>Value Type</label>
                <select name="slab_vtype" id="slabVtype">
                    <option value="fixed">৳ Fixed Amount</option>
                    <option value="percent">% Percentage</option>
                </select>
            </div>
        </div>
        <div style="background:#f0f4ff;border-radius:10px;padding:12px;font-size:12px;color:#3d5a99;margin-bottom:12px">
            <b>Example:</b><br>
            Charge ৳10–৳1000 → Fixed ৳10<br>
            Charge ৳1001–৳5000 → Fixed ৳20<br>
            Commission ৳0–৳99999 → Percent 2%
        </div>
        <div class="modal-footer">
            <button type="button" class="btn" style="background:#f5f5f5;color:#555" onclick="closeM('slabModal')">Cancel</button>
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save</button>
        </div>
    </form>
</div>
</div>

<script>
function openM(id){document.getElementById(id).classList.add('show')}
function closeM(id){document.getElementById(id).classList.remove('show')}
document.querySelectorAll('.modal-bg').forEach(m=>m.addEventListener('click',e=>{if(e.target===m)m.classList.remove('show')}));

// Cat modal
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||'#1a3c8f';
    document.getElementById('catComm').value=c.commission||0;
    document.getElementById('catSort').value=c.sort_order||0;
    document.getElementById('catActive').value=c.is_active;
    document.getElementById('catExLogo').value=c.logo||'';
    const p=document.getElementById('catLogoPreview');
    p.innerHTML=c.logo?`<img src="<?= SITE_URL ?>/${c.logo}" style="width:100%;height:100%;object-fit:contain;border-radius:12px">`:(c.icon||'🧾');
    openM('catModal');
}
document.getElementById('catModal').querySelector('.close-btn').onclick=()=>{
    document.getElementById('catMT').textContent='Add Category';
    document.getElementById('catId').value='';
    document.getElementById('catLogoPreview').textContent='🧾';
    closeM('catModal');
};

// Prov modal
function openProvM(){
    document.getElementById('provMT').textContent='Add Provider';
    ['provId','provName','provCode'].forEach(i=>document.getElementById(i).value='');
    document.getElementById('provIcon').value='🏢';
    document.getElementById('provColor').value='#1a3c8f';
    document.getElementById('provSort').value='0';
    document.getElementById('provActive').value='1';
    document.getElementById('delProvBtn').style.display='none';
    document.getElementById('provExLogo').value='';
    document.getElementById('provLogoPreview').textContent='🏢';
    openM('provModal');
}
function openEditProvM(p){
    document.getElementById('provMT').textContent='Edit Provider';
    document.getElementById('provId').value=p.id;
    document.getElementById('provName').value=p.name;
    document.getElementById('provCode').value=p.code||'';
    document.getElementById('provIcon').value=p.icon||'🏢';
    document.getElementById('provColor').value=p.color||'#1a3c8f';
    document.getElementById('provSort').value=p.sort_order||0;
    document.getElementById('provActive').value=p.is_active;
    document.getElementById('delProvBtn').style.display='flex';
    document.getElementById('delProvId').value=p.id;
    document.getElementById('provExLogo').value=p.logo||'';
    const pr=document.getElementById('provLogoPreview');
    pr.innerHTML=p.logo?`<img src="<?= SITE_URL ?>/${p.logo}" style="width:100%;height:100%;object-fit:contain;border-radius:12px">`:(p.icon||'🏢');
    openM('provModal');
}
function delProv(){if(confirm('Delete?'))document.getElementById('delProvForm').submit()}

// Slab modal
function openSlabM(catId){
    document.getElementById('slabMT').textContent='Add Slab';
    document.getElementById('slabId').value='';
    document.getElementById('slabCatId').value=catId;
    document.getElementById('slabType').value='charge';
    document.getElementById('slabFrom').value='0';
    document.getElementById('slabTo').value='99999';
    document.getElementById('slabValue').value='0';
    document.getElementById('slabVtype').value='fixed';
    openM('slabModal');
}
function openSlabMEdit(sl){
    document.getElementById('slabMT').textContent='Edit Slab';
    document.getElementById('slabId').value=sl.id;
    document.getElementById('slabCatId').value=sl.category_id;
    document.getElementById('slabType').value=sl.type;
    document.getElementById('slabFrom').value=sl.amount_from;
    document.getElementById('slabTo').value=sl.amount_to;
    document.getElementById('slabValue').value=sl.value;
    document.getElementById('slabVtype').value=sl.value_type;
    openM('slabModal');
}

function toggleSlabs(id, name){
    // Close all others
    document.querySelectorAll('.slab-panel').forEach(p=>{
        if(p.id!=='slabs'+id) p.classList.remove('open');
    });
    const el=document.getElementById('slabs'+id);
    el.classList.toggle('open');
    if(el.classList.contains('open')) el.scrollIntoView({behavior:'smooth',block:'nearest'});
}

function previewLogo(input,previewId){
    if(!input.files||!input.files[0])return;
    const r=new FileReader();
    r.onload=e=>{const p=document.getElementById(previewId);p.innerHTML=`<img src="${e.target.result}" style="width:100%;height:100%;object-fit:contain;border-radius:12px">`};
    r.readAsDataURL(input.files[0]);
}
function previewReceipt(input,id){
    if(!input.files||!input.files[0])return;
    const img=document.getElementById('rpreview'+id);
    const r=new FileReader();
    r.onload=e=>{img.src=e.target.result;img.style.display='block'};
    r.readAsDataURL(input.files[0]);
}
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>
