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

// Tables
try {
    $db->exec("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");
    $db->exec("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");
    $db->exec("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,
        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");
    // Default categories
    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) {}

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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_bill'])) {
    $catId    = intval($_POST['category_id'] ?? 0);
    $provId   = intval($_POST['provider_id'] ?? 0);
    $billNum  = sanitize($_POST['bill_number'] ?? '');
    $billAmt  = floatval($_POST['bill_amount'] ?? 0);
    $mobile   = sanitize($_POST['mobile_number'] ?? '');
    $month    = sanitize($_POST['bill_month'] ?? '');
    $note     = sanitize($_POST['note'] ?? '');

    // Calculate charge from slabs
    $chargeAmt = 0;
    if($catId && $billAmt > 0) {
        $csl=$db->prepare("SELECT * FROM bill_charge_slabs WHERE category_id=? AND type='charge' AND amount_from<=? AND amount_to>=? ORDER BY sort_order LIMIT 1");
        $csl->execute([$catId,$billAmt,$billAmt]); $csl=$csl->fetch();
        if($csl) $chargeAmt=$csl['value_type']==='percent'?round($billAmt*$csl['value']/100,2):$csl['value'];
    }
    $totalDeduct = $billAmt + $chargeAmt;

    if (!$catId || !$billNum || $billAmt <= 0) {
        $error = 'Please fill all required fields.';
    } elseif ($user['balance'] < $totalDeduct) {
        $error = 'Insufficient balance! Required: ৳'.number_format($totalDeduct,2).($chargeAmt>0?' (Bill: ৳'.number_format($billAmt,2).' + Charge: ৳'.number_format($chargeAmt,2).')':'');
    } else {
        $ref = 'BLL'.strtoupper(substr(uniqid(),7));
        $balBefore = floatval($user['balance']);
        $balAfter  = $balBefore - $totalDeduct;
        $db->beginTransaction();
        try {
            $db->prepare("UPDATE users SET balance=balance-? WHERE id=?")->execute([$totalDeduct,$user['id']]);
            $db->prepare("INSERT INTO bill_requests (user_id,category_id,provider_id,bill_number,bill_amount,charge_amount,mobile_number,bill_month,note,reference,balance_before,balance_after) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)")
               ->execute([$user['id'],$catId,$provId?:null,$billNum,$billAmt,$chargeAmt,$mobile,$month,$note,$ref,$balBefore,$balAfter]);
            $db->prepare("INSERT INTO transactions (user_id,type,amount,charge,net_amount,balance_before,balance_after,phone_number,reference,status,note) VALUES (?,?,?,0,?,?,?,?,?,?,?)")
               ->execute([$user['id'],'bill',$billAmt,$billAmt,$balBefore,$balAfter,$mobile,$ref,'pending',$billNum]);
            $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'info')")->execute([$user['id'],'🧾 Bill Pay Request Sent!','Ref: '.$ref]);
            $cat = $db->prepare("SELECT * FROM bill_categories WHERE id=?"); $cat->execute([$catId]); $cat=$cat->fetch();
            $prov = $provId ? $db->prepare("SELECT * FROM bill_providers WHERE id=?") : null;
            if($prov){$prov->execute([$provId]);$prov=$prov->fetch();}
            notifyPending('bill_pay',$user['name'],[
                '🧾 Category'=>($cat['icon']??'').' '.($cat['name']??''),
                '🏢 Provider'=>$prov?($prov['icon'].' '.$prov['name']):'—',
                '📋 Bill No'=>$billNum,'💰 Amount'=>'৳'.number_format($billAmt,2),
                '📱 Mobile'=>$mobile?:('—'),'📅 Month'=>$month?:('—'),
                '📝 Note'=>$note?:('—'),'🔖 Ref'=>$ref,'👤 User'=>$user['name']
            ]);
            $db->commit();
            header('Location: bill-pay.php?success='.urlencode("Bill pay request submitted! Ref: $ref")); exit;
        } catch(Exception $e) { $db->rollBack(); $error='Error: '.$e->getMessage(); }
    }
}

$categories = $db->query("SELECT * FROM bill_categories WHERE is_active=1 ORDER BY sort_order,id")->fetchAll();
$allProviders = $db->query("SELECT * FROM bill_providers WHERE is_active=1 ORDER BY category_id,sort_order,id")->fetchAll();

$myReqs = $db->prepare("SELECT r.*, c.name as cat_name, c.icon as cat_icon, p.name as prov_name FROM bill_requests r JOIN bill_categories c ON r.category_id=c.id LEFT JOIN bill_providers p ON r.provider_id=p.id WHERE r.user_id=? ORDER BY r.created_at DESC LIMIT 30");
$myReqs->execute([$user['id']]); $myReqs=$myReqs->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>Bill Pay</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
*{margin:0;padding:0;box-sizing:border-box;-webkit-tap-highlight-color:transparent}
:root{
            --primary:<?= getSetting('color_primary') ?: '#1a3c8f' ?>;
            --secondary:<?= getSetting('color_secondary') ?: '#f5a623' ?>;
            --dark:<?= getSetting('color_dark') ?: '#0d1f4e' ?>;
        }
body{font-family:'Segoe UI',sans-serif;background:#f5f7fa;color:#333;padding-bottom:90px}
.hdr{background:linear-gradient(135deg,var(--dark),var(--primary));padding:0 18px;position:sticky;top:0;z-index:100}
.hdr-in{display:flex;align-items:center;height:56px;max-width:480px;margin:0 auto;gap:12px}
.back-btn{background:none;border:none;color:white;font-size:20px;cursor:pointer;width:36px;height:36px;display:flex;align-items:center;justify-content:center}
.hdr-title{color:white;font-size:17px;font-weight:800;flex:1}
.bal-pill{background:rgba(255,255,255,0.18);border-radius:20px;padding:5px 12px;font-size:12px;font-weight:800;color:white}
.tabs{display:flex;background:white;border-bottom:1px solid #eee;position:sticky;top:56px;z-index:50}
.tab{flex:1;padding:13px;text-align:center;font-size:13px;font-weight:700;color:#aaa;cursor:pointer;border-bottom:2px solid transparent;transition:0.2s}
.tab.on{color:var(--primary);border-bottom-color:var(--primary)}
.page{max-width:480px;margin:0 auto;padding:16px}
.alert{padding:12px 16px;border-radius:12px;font-size:13px;font-weight:600;margin-bottom:14px}
.alert-ok{background:#f0fff4;color:#276749;border:1px solid #c6f6d5}
.alert-err{background:#fff5f5;color:#c53030;border:1px solid #fed7d7}
.sec{background:white;border-radius:16px;padding:16px;margin-bottom:14px;box-shadow:0 2px 8px rgba(0,0,0,0.05)}
.sec-title{font-size:14px;font-weight:800;color:var(--dark);margin-bottom:14px;display:flex;align-items:center;gap:8px}

/* Category grid */
.cat-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:10px}
.cat-card{border:2px solid #f0f0f0;border-radius:14px;padding:14px 10px;text-align:center;cursor:pointer;transition:0.2s;background:white}
.cat-card:active{transform:scale(0.96)}
.cat-card.sel{border-color:var(--primary);background:#f0f4ff}
.cat-icon{font-size:28px;margin-bottom:6px}
.cat-name{font-size:11px;font-weight:700;color:#555}

/* Provider grid */
.prov-grid{display:grid;grid-template-columns:1fr 1fr;gap:8px}
.prov-item{display:flex;align-items:center;gap:10px;padding:11px 13px;border:2px solid #f0f0f0;border-radius:12px;cursor:pointer;transition:0.2s;background:white}
.prov-item.sel{border-color:var(--primary);background:#f0f4ff}
.prov-item:active{transform:scale(0.97)}
.prov-logo{width:32px;height:32px;border-radius:8px;object-fit:contain;flex-shrink:0}
.prov-icon{width:32px;height:32px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0}
.prov-name{font-size:12px;font-weight:700;color:#333}

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

/* Summary */
.summary{background:linear-gradient(135deg,#f0f4ff,#e8ecf8);border-radius:14px;padding:14px;margin-bottom:14px}
.sum-row{display:flex;justify-content:space-between;align-items:center;padding:6px 0;border-bottom:1px solid rgba(26,60,143,0.08)}
.sum-row:last-child{border:none}
.sum-lbl{font-size:12px;color:#666;font-weight:600}
.sum-val{font-size:13px;font-weight:700;color:#1a1a2e;text-align:right}

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

/* Steps nav */
.step-bar{display:flex;align-items:center;background:white;border-radius:14px;padding:12px 16px;margin-bottom:16px;box-shadow:0 1px 6px rgba(0,0,0,0.06)}
.step-item{display:flex;align-items:center;gap:6px;flex:1}
.step-num{width:24px;height:24px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:800;flex-shrink:0;transition:0.3s}
.step-num.done{background:var(--primary);color:white}
.step-num.active{background:#e8ecf4;color:var(--primary);border:2px solid var(--primary)}
.step-num.pend{background:#f0f0f0;color:#ccc}
.step-lbl{font-size:10px;font-weight:700;color:#aaa}
.step-lbl.active{color:var(--primary)}
.step-lbl.done{color:#888}
.step-line{width:16px;height:2px;background:#eee;flex-shrink:0}

/* History */
.req-card{background:white;border-radius:12px;margin-bottom:10px;overflow:hidden;border:1px solid #f0f0f0;box-shadow:0 1px 4px rgba(0,0,0,0.04)}
.req-head{display:flex;align-items:center;gap:12px;padding:13px 14px;cursor:pointer}
.req-det{display:none;padding:12px 14px;border-top:1px solid #f5f5f5;background:#fafbff}
.req-det.open{display:block}
.s-badge{font-size:11px;font-weight:700;padding:3px 10px;border-radius:20px}
.s-pending{background:#fffbeb;color:#d69e2e}
.s-success{background:#f0fff4;color:#276749}
.s-failed{background:#fff5f5;color:#e53e3e}
.s-processing{background:#ebf8ff;color:#2b6cb0}
.dg{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:10px}
.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}
.receipt-img{width:100%;border-radius:10px;margin-top:8px;cursor:pointer}

@keyframes slideUp{from{opacity:0;transform:translateY(16px)}to{opacity:1;transform:translateY(0)}}
.anim{animation:slideUp 0.3s ease}
</style>
</head>
<body>
<div class="hdr">
    <div class="hdr-in">
        <button class="back-btn" onclick="history.back()"><i class="fas fa-arrow-left"></i></button>
        <div class="hdr-title">🧾 Bill Pay</div>
        <div class="bal-pill">৳<?= number_format($user['balance'],2) ?></div>
    </div>
</div>
<div class="tabs">
    <div class="tab on" onclick="switchTab('new',this)">📝 New Request</div>
    <div class="tab" onclick="switchTab('history',this)">📋 My Bills (<?= count($myReqs) ?>)</div>
</div>

<!-- NEW REQUEST -->
<div id="tab-new">
<div class="page">
<?php if($error): ?><div class="alert alert-err">❌ <?= htmlspecialchars($error) ?></div><?php endif; ?>
<?php if($success): ?><div class="alert alert-ok">✅ <?= htmlspecialchars($success) ?></div><?php endif; ?>

<!-- Step bar -->
<div class="step-bar" id="stepBar">
    <div class="step-item"><div class="step-num active" id="sn1">1</div><div class="step-lbl active" id="sl1">Category</div></div>
    <div class="step-line"></div>
    <div class="step-item"><div class="step-num pend" id="sn2">2</div><div class="step-lbl" id="sl2">Provider</div></div>
    <div class="step-line"></div>
    <div class="step-item"><div class="step-num pend" id="sn3">3</div><div class="step-lbl" id="sl3">Details</div></div>
</div>

<!-- STEP 1: Category -->
<div id="s1" class="anim">
    <div class="sec">
        <div class="sec-title"><i class="fas fa-th-large" style="color:var(--primary)"></i> Select Category</div>
        <div class="cat-grid">
        <?php foreach($categories as $cat): ?>
        <div class="cat-card" data-id="<?= $cat['id'] ?>" data-name="<?= htmlspecialchars($cat['name'],ENT_QUOTES) ?>" data-icon="<?= $cat['icon'] ?>" onclick="selCat(this)">
            <?php if($cat['logo']): ?>
            <img src="<?= SITE_URL ?>/<?= htmlspecialchars($cat['logo']) ?>" style="width:42px;height:42px;border-radius:10px;object-fit:contain;display:block;margin:0 auto 6px">
            <?php else: ?>
            <div class="cat-icon"><?= $cat['icon'] ?></div>
            <?php endif; ?>
            <div class="cat-name"><?= htmlspecialchars($cat['name']) ?></div>
        </div>
        <?php endforeach; ?>
        </div>
    </div>
</div>

<!-- STEP 2: Provider -->
<div id="s2" style="display:none">
    <div class="sec anim">
        <div class="sec-title">
            <button onclick="goStep(1)" style="background:#f0f4ff;border:none;color:var(--primary);width:28px;height:28px;border-radius:8px;cursor:pointer;display:flex;align-items:center;justify-content:center"><i class="fas fa-arrow-left"></i></button>
            <span id="s2Title">Select Provider</span>
        </div>
        <div class="prov-grid" id="provList"></div>
        <div style="margin-top:10px">
            <button onclick="skipProvider()" style="width:100%;padding:11px;background:#f8fafc;border:2px dashed #e8ecf4;border-radius:12px;font-size:13px;font-weight:700;color:#888;cursor:pointer">
                <i class="fas fa-forward"></i> Skip — Provider not listed
            </button>
        </div>
    </div>
</div>

<!-- STEP 3: Details Form -->
<div id="s3" style="display:none">
    <div id="summaryBox" class="summary anim"></div>
    <form method="POST">
        <input type="hidden" name="submit_bill" value="1">
        <input type="hidden" name="category_id" id="fCatId">
        <input type="hidden" name="provider_id" id="fProvId">
        <div class="sec anim">
            <div class="sec-title">
                <button type="button" onclick="goStep(2)" style="background:#f0f4ff;border:none;color:var(--primary);width:28px;height:28px;border-radius:8px;cursor:pointer;display:flex;align-items:center;justify-content:center"><i class="fas fa-arrow-left"></i></button>
                <span>Bill Details</span>
            </div>
            <div class="fg">
                <label>Bill / Account Number *</label>
                <input type="text" name="bill_number" required placeholder="Enter bill/account number">
            </div>
            <div class="fg">
                <label>Bill Amount (৳) *</label>
                <input type="number" name="bill_amount" step="0.01" min="1" required placeholder="0.00"
                    id="fBillAmt" oninput="updateAmtSummary(this.value)">
                <?php if($uc && floatval($uc['rate'])>0): ?>
                <div id="billAmtUC" style="font-size:11px;color:#aaa;margin-top:4px"></div>
                <?php endif; ?>
            </div>
            <div class="fg">
                <label>Mobile Number</label>
                <input type="tel" name="mobile_number" placeholder="01XXXXXXXXX">
            </div>
            <div class="fg">
                <label>Bill Month</label>
                <select name="bill_month">
                    <option value="">— Select Month —</option>
                    <?php
                    $months=['January','February','March','April','May','June','July','August','September','October','November','December'];
                    $curYear=date('Y'); $curMon=date('n');
                    for($y=$curYear;$y>=$curYear-1;$y--) {
                        $maxM = ($y==$curYear)?$curMon:12;
                        for($m=$maxM;$m>=1;$m--) {
                            echo "<option value='{$months[$m-1]} $y'>{$months[$m-1]} $y</option>";
                        }
                    }
                    ?>
                </select>
            </div>
            <div class="fg">
                <label>Note <span style="color:#aaa;font-weight:400;font-size:10px">(optional)</span></label>
                <textarea name="note" placeholder="Any additional information..."></textarea>
            </div>
        </div>
        <button type="submit" class="submit-btn"><i class="fas fa-paper-plane"></i> Submit Bill Pay</button>
    </form>
</div>
</div>
</div>

<!-- HISTORY -->
<div id="tab-history" style="display:none">
<div class="page">
    <?php if(empty($myReqs)): ?>
    <div style="text-align:center;padding:40px;color:#ccc"><i class="fas fa-receipt" style="font-size:36px;display:block;margin-bottom:10px"></i>No bill pay requests yet</div>
    <?php else: foreach($myReqs as $r): ?>
    <div class="req-card">
        <div class="req-head" onclick="tR(<?= $r['id'] ?>)">
            <div style="width:40px;height:40px;border-radius:11px;background:#f0f4ff;display:flex;align-items:center;justify-content:center;font-size:18px;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;margin-top:2px"><?= htmlspecialchars($r['bill_number']) ?> · <?= date('d M, h:i A',strtotime($r['created_at'])) ?></div>
            </div>
            <div style="text-align:right;flex-shrink:0;margin-right:6px">
                <div style="font-size:14px;font-weight:800;color:#e53e3e">৳<?= number_format($r['bill_amount'],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;transition:0.2s"></i>
        </div>
        <div class="req-det" id="rdet<?= $r['id'] ?>">
            <div class="dg">
                <div class="dg-i"><div class="dg-l">Bill No</div><div class="dg-v"><?= 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) ?><?php if($uc && floatval($uc['rate'])>0): ?><br><span style="font-size:10px;color:#aaa">≈ <?= htmlspecialchars($uc['symbol']) ?><?= number_format($r['bill_amount']*floatval($uc['rate']),2) ?> <?= $uc['code'] ?></span><?php endif; ?></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; ?>
                <?php $totalPaid=floatval($r['bill_amount'])+floatval($r['charge_amount']??0); if($totalPaid>$r['bill_amount']): ?><div class="dg-i"><div class="dg-l">Total Paid</div><div class="dg-v" style="color:#e53e3e;font-weight:800">৳<?= number_format($totalPaid,2) ?></div></div><?php endif; ?>
                <?php if($r['mobile_number']): ?><div class="dg-i"><div class="dg-l">Mobile</div><div class="dg-v"><?= $r['mobile_number'] ?></div></div><?php endif; ?>
                <?php if($r['bill_month']): ?><div class="dg-i"><div class="dg-l">Month</div><div class="dg-v"><?= htmlspecialchars($r['bill_month']) ?></div></div><?php endif; ?>
                <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:8px;border:1px solid #f0f0f0"><?= nl2br(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;border-left:3px solid #d69e2e"><b>Admin Note:</b> <?= htmlspecialchars($r['admin_note']) ?></div><?php endif; ?>
            <?php if($r['receipt_image']): ?>
            <div style="margin-top:8px;font-size:11px;color:#aaa;font-weight:700;margin-bottom:4px">📷 Receipt</div>
            <img src="<?= SITE_URL ?>/<?= htmlspecialchars($r['receipt_image']) ?>" class="receipt-img" onclick="window.open(this.src)">
            <?php endif; ?>
        </div>
    </div>
    <?php endforeach; endif; ?>
</div>
</div>

<script>
const CATS = <?= json_encode(array_values($categories),JSON_UNESCAPED_UNICODE) ?>;
<?php
$allBillSlabs = $db->query("SELECT * FROM bill_charge_slabs ORDER BY category_id,type,sort_order")->fetchAll();
?>
const BILL_SLABS = <?= json_encode($allBillSlabs, JSON_UNESCAPED_UNICODE) ?>;
const PROVS = <?= json_encode(array_values($allProviders),JSON_UNESCAPED_UNICODE) ?>;
const UC_RATE = <?= $uc?floatval($uc['rate']):0 ?>;
const UC_SYM  = "<?= $uc?htmlspecialchars($uc['symbol'],ENT_QUOTES):'৳' ?>";
const UC_CODE = "<?= $uc?$uc['code']:'' ?>";
const CURRENCY = '<?= CURRENCY ?>';

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

function goStep(n) {
    for(let i=1;i<=3;i++) document.getElementById('s'+i).style.display=i===n?'block':'none';
    curStep=n; updateStepBar(); window.scrollTo({top:0,behavior:'smooth'});
}
function updateStepBar() {
    for(let i=1;i<=3;i++) {
        const sn=document.getElementById('sn'+i), sl=document.getElementById('sl'+i);
        if(i<curStep){sn.className='step-num done';sn.innerHTML='✓';sl.className='step-lbl done';}
        else if(i===curStep){sn.className='step-num active';sn.textContent=i;sl.className='step-lbl active';}
        else{sn.className='step-num pend';sn.textContent=i;sl.className='step-lbl';}
    }
}

function selCat(el) {
    document.querySelectorAll('.cat-card').forEach(c=>c.classList.remove('sel'));
    el.classList.add('sel');
    sel.cat={id:el.dataset.id, name:el.dataset.name, icon:el.dataset.icon};
    // Load providers
    const provs = PROVS.filter(p=>p.category_id==sel.cat.id);
    const list = document.getElementById('provList');
    document.getElementById('s2Title').textContent = sel.cat.icon+' '+sel.cat.name+' — Provider';
    if(provs.length===0){skipProvider();return;}
    list.innerHTML = provs.map(p=>`
    <div class="prov-item" data-id="${p.id}" data-name="${p.name}" data-icon="${p.icon||'🏢'}" onclick="selProv(this)">
        ${p.logo?`<img src="<?= SITE_URL ?>/${p.logo}" class="prov-logo" style="background:${p.color}18;padding:4px">`
                :`<div class="prov-icon" style="background:${p.color}18">${p.icon||'🏢'}</div>`}
        <span class="prov-name">${p.name}</span>
    </div>`).join('');
    setTimeout(()=>goStep(2),80);
}

function selProv(el) {
    document.querySelectorAll('.prov-item').forEach(p=>p.classList.remove('sel'));
    el.classList.add('sel');
    sel.prov={id:el.dataset.id, name:el.dataset.name, icon:el.dataset.icon};
    gotoDetails();
}
function skipProvider() {
    sel.prov=null;
    gotoDetails();
}
function gotoDetails() {
    document.getElementById('fCatId').value = sel.cat.id;
    document.getElementById('fProvId').value = sel.prov?.id||'';
    let html=`<div class="sum-row"><span class="sum-lbl">${sel.cat.icon} Category</span><span class="sum-val">${sel.cat.name}</span></div>`;
    if(sel.prov) html+=`<div class="sum-row"><span class="sum-lbl">${sel.prov.icon} Provider</span><span class="sum-val">${sel.prov.name}</span></div>`;
    html+=`<div class="sum-row"><span class="sum-lbl">💰 Amount</span><span class="sum-val" id="sumAmt" style="color:var(--primary)">—</span></div>`;
    document.getElementById('summaryBox').innerHTML=html;
    goStep(3);
}
function getChargeForAmt(catId, amt) {
    const slab = BILL_SLABS.find(s=>s.category_id==catId && s.type==='charge' && parseFloat(s.amount_from)<=amt && parseFloat(s.amount_to)>=amt);
    if(!slab) return 0;
    return slab.value_type==='percent' ? Math.round(amt * parseFloat(slab.value) / 100 * 100)/100 : parseFloat(slab.value);
}
function getCommForAmt(catId, amt) {
    const slab = BILL_SLABS.find(s=>s.category_id==catId && s.type==='commission' && parseFloat(s.amount_from)<=amt && parseFloat(s.amount_to)>=amt);
    if(!slab) return 0;
    return slab.value_type==='percent' ? Math.round(amt * parseFloat(slab.value) / 100 * 100)/100 : parseFloat(slab.value);
}
function updateAmtSummary(v) {
    const amt = parseFloat(v)||0;
    const catId = document.getElementById('fCatId').value;
    const charge = amt>0&&catId ? getChargeForAmt(catId, amt) : 0;
    const comm   = amt>0&&catId ? getCommForAmt(catId, amt) : 0;
    const total  = amt + charge;

    // Update summary box
    const el=document.getElementById('sumAmt');
    if(el) {
        let txt = amt>0 ? CURRENCY+amt.toFixed(2) : '—';
        if(charge>0) txt += ` <span style="color:#e53e3e;font-size:11px">+ ৳${charge.toFixed(2)} charge</span>`;
        el.innerHTML = txt;
    }
    // Charge/commission info under input
    const uc=document.getElementById('billAmtUC');
    if(uc) {
        let info = [];
        if(amt>0&&UC_RATE>0) info.push('≈ '+UC_SYM+(amt*UC_RATE).toFixed(2)+' '+UC_CODE);
        if(charge>0) info.push('<span style="color:#e53e3e;font-weight:700">💳 Charge: ৳'+charge.toFixed(2)+'</span>');
        if(comm>0)   info.push('<span style="color:#276749;font-weight:700">💸 Commission: +৳'+comm.toFixed(2)+'</span>');
        if(charge>0) info.push('<span style="color:#e53e3e;font-weight:700">Total deduct: ৳'+total.toFixed(2)+'</span>');
        uc.innerHTML = info.join(' &nbsp;·&nbsp; ');
    }
}

function switchTab(tab,el) {
    document.querySelectorAll('.tab').forEach(t=>t.classList.remove('on'));
    el.classList.add('on');
    document.getElementById('tab-new').style.display=tab==='new'?'block':'none';
    document.getElementById('tab-history').style.display=tab==='history'?'block':'none';
}
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)':'';
}
</script>
<?php include 'includes/bottom_nav.php'; ?>
<script>document.addEventListener("DOMContentLoaded",function(){ if(window.pageReady) window.pageReady(); });</script>
</body>
</html>
