<?php
ob_start();
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include('includes/function.php');

$admin    = $_SESSION["admin_" . $dbname];
$usertype = $_SESSION["usertype"];
$username = $_SESSION["username_" . $dbname];
$tourname = $_SESSION["tourname"];
$tourcode = $_SESSION['tourcode'];

if ($usertype != 1) {
    include("includes/menu_rights.php");
}

$zdb = $_SESSION["zdbyear_" . $dbname];
mysqli_select_db($conn, $zdb);

$tdate = date("Y-m-d");

// ---- Helpers: never let one bad query take down the whole dashboard ----
function dashVal($conn, $sql) {
    $r = @mysqli_query($conn, $sql);
    if (!$r) return 0;
    $row = mysqli_fetch_row($r);
    return ($row && $row[0] !== null) ? $row[0] : 0;
}
function dashRows($conn, $sql) {
    $r = @mysqli_query($conn, $sql);
    $out = [];
    if ($r) {
        while ($row = mysqli_fetch_assoc($r)) $out[] = $row;
    }
    return $out;
}
function inr($v) {
    return "₹ " . number_format((float)$v, 0, '.', ',');
}
// Verified against ledger_fr.php: closing balance = signed opening balance + sum of actran.amount.
// Negative result = Debit (DR), positive = Credit (CR) - same convention the existing Ledger report uses.
function acctBalances($conn, $grpcodes) {
    $codes = is_array($grpcodes) ? $grpcodes : [$grpcodes];
    $in = "'" . implode("','", array_map(function ($g) use ($conn) {
        return mysqli_real_escape_string($conn, $g);
    }, $codes)) . "'";
    $sql = "SELECT a.accode, a.name,
                   (CASE WHEN a.dc = 'D' THEN -a.openbal ELSE a.openbal END) + COALESCE(SUM(t.amount), 0) AS balance
            FROM accmast a
            LEFT JOIN actran t ON t.accode = a.accode AND t.retdate = '0000-00-00' AND t.flatno = ''
            WHERE a.grpcode IN ($in)
            GROUP BY a.accode, a.name, a.openbal, a.dc";
    return dashRows($conn, $sql);
}

// ---- Tour filter from masters ----
$tourFilter   = isset($_GET['tour']) && $_GET['tour'] !== '' ? mysqli_real_escape_string($conn, $_GET['tour']) : '';
$tourcond     = $tourFilter !== '' ? "AND tourno = '$tourFilter'" : '';
$visatourcond = $tourFilter !== '' ? "AND tour = '$tourFilter'" : '';
$tourList     = dashRows($conn, "SELECT code, name, fromdate, todate FROM tour ORDER BY code");

// ---- Period filter: when a tour is selected use its fromdate/todate from master ----
$tourDates = ['fromdate' => '', 'todate' => ''];
if ($tourFilter !== '') {
    foreach ($tourList as $t) {
        if ($t['code'] === $tourFilter) { $tourDates = $t; break; }
    }
}
if (isset($_GET['from']) && $_GET['from'] !== '') {
    $fromdt = $_GET['from'];
    $todt   = isset($_GET['to']) && $_GET['to'] !== '' ? $_GET['to'] : date("Y-m-t");
} elseif ($tourFilter !== '' && !empty($tourDates['fromdate']) && $tourDates['fromdate'] !== '0000-00-00') {
    $fromdt = $tourDates['fromdate'];
    $todt   = !empty($tourDates['todate']) && $tourDates['todate'] !== '0000-00-00' ? $tourDates['todate'] : date("Y-m-t");
} else {
    $fromdt = date("Y-m-01");
    $todt   = date("Y-m-t");
}
$chartyear = isset($_GET['year']) ? (int)$_GET['year'] : (int)date("Y", strtotime($fromdt));

// ---- Business snapshot (all-time master counts) ----
$totBookings  = dashVal($conn, "SELECT COUNT(*) FROM bookform WHERE (cancdate = '0000-00-00' OR cancdate IS NULL OR cancdate = '') $tourcond");
$totCancelled = dashVal($conn, "SELECT COUNT(*) FROM bookform WHERE cancdate != '0000-00-00' AND cancdate IS NOT NULL AND cancdate != '' $tourcond");
$totFitInv    = dashVal($conn, "SELECT COUNT(*) FROM pax");
$totCustomers = dashVal($conn, "SELECT COUNT(*) FROM accmast WHERE grpcode = '010'");
$totAgents    = dashVal($conn, "SELECT COUNT(*) FROM accmast WHERE grpcode = '044'");
$totSuppliers = dashVal($conn, "SELECT COUNT(*) FROM accmast WHERE grpcode = '009'");
$totBanks     = dashVal($conn, "SELECT COUNT(*) FROM accmast WHERE grpcode = '001'");
$totHotels    = dashVal($conn, "SELECT COUNT(*) FROM hotels");
// Pending tasks removed from dashboard per owner request
// $pendingTasks = dashVal($conn, "SELECT COUNT(*) FROM todo WHERE done != 'Y' OR done IS NULL OR done = ''");

// ---- Revenue: tour selected = all bookings for that tour; no tour = date range ----
if ($tourFilter !== '') {
    $hajRevenue = (float) dashVal($conn, "SELECT COALESCE(SUM(netamt),0) FROM bookform WHERE (cancdate='0000-00-00' OR cancdate IS NULL OR cancdate='') $tourcond");
} else {
    $hajRevenue = (float) dashVal($conn, "SELECT COALESCE(SUM(netamt),0) FROM bookform WHERE vouchdt BETWEEN '$fromdt' AND '$todt' AND (cancdate='0000-00-00' OR cancdate IS NULL OR cancdate='')");
}

// ---- Class-wise breakdown for selected tour ----
$classBreakdown = [];
if ($tourFilter !== '') {
    $classBreakdown = dashRows($conn, "SELECT batchno, COUNT(*) as pax, COALESCE(SUM(netamt),0) as rev
        FROM bookform WHERE tourno='$tourFilter' AND (cancdate='0000-00-00' OR cancdate IS NULL OR cancdate='')
        GROUP BY batchno ORDER BY batchno");
}

$tiktAmt  = (float) dashVal($conn, "SELECT COALESCE(SUM(tiktamt),0)     FROM pax WHERE `date` BETWEEN '$fromdt' AND '$todt'");
$hotelAmt = (float) dashVal($conn, "SELECT COALESCE(SUM(hotelinramt),0) FROM pax WHERE `date` BETWEEN '$fromdt' AND '$todt'");
$foodAmt  = (float) dashVal($conn, "SELECT COALESCE(SUM(foodinramt),0)  FROM pax WHERE `date` BETWEEN '$fromdt' AND '$todt'");
$laundAmt = (float) dashVal($conn, "SELECT COALESCE(SUM(laundinramt),0) FROM pax WHERE `date` BETWEEN '$fromdt' AND '$todt'");
$transAmt = (float) dashVal($conn, "SELECT COALESCE(SUM(transinramt),0) FROM pax WHERE `date` BETWEEN '$fromdt' AND '$todt'");
$visaAmt  = (float) dashVal($conn, "SELECT COALESCE(SUM(visaamt),0)     FROM pax WHERE `date` BETWEEN '$fromdt' AND '$todt'");
$fitRevenue = $tiktAmt + $hotelAmt + $foodAmt + $laundAmt + $transAmt + $visaAmt;
$grossRevenue = $hajRevenue + $fitRevenue;

// ---- Accounts: receivables, payables, bank/cash, expense (verified ledger formula) ----
$custBal = acctBalances($conn, '010');
$depMap = [];
foreach (dashRows($conn, "SELECT accode, MAX(depdate) AS maxdep FROM bookform WHERE accode != '' GROUP BY accode") as $r) {
    $depMap[$r['accode']] = $r['maxdep'];
}
$receivableTotal = 0; $receivableCount = 0; $overdueTotal = 0; $overdueCount = 0;
foreach ($custBal as $r) {
    $bal = (float)$r['balance'];
    if ($bal < 0) {
        $receivableTotal += abs($bal);
        $receivableCount++;
        $maxdep = isset($depMap[$r['accode']]) ? $depMap[$r['accode']] : null;
        if ($maxdep && $maxdep != '0000-00-00' && $maxdep < $tdate) {
            $overdueTotal += abs($bal);
            $overdueCount++;
        }
    }
}

$supBal = acctBalances($conn, '009');
$payableTotal = 0; $payableCount = 0;
foreach ($supBal as $r) {
    $bal = (float)$r['balance'];
    if ($bal > 0) { $payableTotal += $bal; $payableCount++; }
}

$bankCashBalance = 0;
foreach (acctBalances($conn, ['001', '002']) as $r) {
    $bankCashBalance += -1 * (float)$r['balance'];
}

$totalExpensePeriod = -1 * (float) dashVal($conn, "SELECT SUM(t.amount) FROM actran t
                                                     JOIN accmast a2 ON t.accode = a2.accode
                                                     WHERE a2.grpcode = '012' AND t.date BETWEEN '$fromdt' AND '$todt'
                                                     AND t.retdate = '0000-00-00' AND t.flatno = ''");

// ---- Pilgrim doc counts (alerts only — chart removed per owner request) ----
$docTotal         = (int) dashVal($conn, "SELECT COUNT(*) FROM visaform WHERE name != '' $visatourcond");
$docIncomplete    = (int) dashVal($conn, "SELECT COUNT(*) FROM visaform WHERE name != '' $visatourcond AND NOT (COALESCE(chkpassport,0)=1 AND COALESCE(chkpan,0)=1 AND COALESCE(chkaadhaar,0)=1 AND COALESCE(chkhealth,0)=1 AND COALESCE(chkvisarec,0)=1 AND COALESCE(chkphoto,0)=1)");
$missVisa         = (int) dashVal($conn, "SELECT COUNT(*) FROM visaform WHERE name != '' $visatourcond AND COALESCE(chkvisarec,0) = 0");
$passportExpiring = (int) dashVal($conn, "SELECT COUNT(*) FROM visaform WHERE expdate IS NOT NULL AND expdate != '0000-00-00' $visatourcond AND expdate BETWEEN '$tdate' AND DATE_ADD('$tdate', INTERVAL 30 DAY)");

// ---- Monthly chart data for selected year (FIT vs Haj/Umrah revenue) ----
$fitByMonth = array_fill(1, 12, 0);
$hajByMonth = array_fill(1, 12, 0);
for ($m = 1; $m <= 12; $m++) {
    $fitByMonth[$m] = (float) dashVal($conn, "SELECT COALESCE(SUM(tiktamt),0)+COALESCE(SUM(hotelinramt),0)+COALESCE(SUM(foodinramt),0)+COALESCE(SUM(laundinramt),0)+COALESCE(SUM(transinramt),0)+COALESCE(SUM(visaamt),0) FROM pax WHERE MONTH(`date`) = $m AND YEAR(`date`) = $chartyear");
    $hajByMonth[$m] = (float) dashVal($conn, "SELECT COALESCE(SUM(netamt),0) FROM bookform WHERE MONTH(vouchdt)=$m AND YEAR(vouchdt)=$chartyear AND (cancdate='0000-00-00' OR cancdate IS NULL OR cancdate='') $tourcond");

}

// ---- Bookings trend - trailing 6 months (counts) ----
$trendLabels = []; $trendHaj = []; $trendFit = [];
for ($i = 5; $i >= 0; $i--) {
    $ym = date("Y-m", strtotime("-$i months"));
    $trendLabels[] = date("M-y", strtotime("-$i months"));
    $trendHaj[] = (int) dashVal($conn, "SELECT COUNT(*) FROM bookform WHERE DATE_FORMAT(vouchdt,'%Y-%m') = '$ym' AND (cancdate = '0000-00-00' OR cancdate IS NULL OR cancdate = '') $tourcond");
    $trendFit[] = (int) dashVal($conn, "SELECT COUNT(*) FROM pax WHERE DATE_FORMAT(`date`,'%Y-%m') = '$ym'");
}

// ---- Revenue forecast - next 6 months, from already-confirmed bookings (depdate), not a statistical guess ----
$forecastLabels = []; $forecastAmt = [];
for ($i = 0; $i <= 5; $i++) {
    $mstart = date("Y-m-01", strtotime("+$i months"));
    $mend   = date("Y-m-t", strtotime("+$i months"));
    $forecastLabels[] = date("M Y", strtotime($mstart));
    $forecastAmt[] = (float) dashVal($conn, "SELECT COALESCE(SUM(netamt),0) FROM bookform WHERE depdate BETWEEN '$mstart' AND '$mend' AND (cancdate = '0000-00-00' OR cancdate IS NULL OR cancdate = '') $tourcond");
}

// ---- Operational widgets ----
$upcomingDep = dashRows($conn, "SELECT vouchno, haji, groupno, tourno, DATE_FORMAT(depdate,'%d-%m-%Y') AS depdt
                                 FROM bookform
                                 WHERE depdate BETWEEN '$tdate' AND DATE_ADD('$tdate', INTERVAL 30 DAY)
                                 AND (cancdate = '0000-00-00' OR cancdate IS NULL OR cancdate = '') $tourcond
                                 ORDER BY depdate ASC LIMIT 8");

$dep7 = dashVal($conn, "SELECT COUNT(DISTINCT groupno) FROM bookform WHERE depdate BETWEEN '$tdate' AND DATE_ADD('$tdate', INTERVAL 7 DAY)
                         AND (cancdate = '0000-00-00' OR cancdate IS NULL OR cancdate = '') $tourcond");

$recentBookings = dashRows($conn, "SELECT vouchno, haji, DATE_FORMAT(vouchdt,'%d-%m-%Y') AS vdt, netamt
                                    FROM bookform WHERE 1=1 $tourcond ORDER BY vouchno DESC LIMIT 8");

// Pending tasks section removed from dashboard per owner request
// $recentTasks = dashRows($conn, "SELECT vouchno, task, DATE_FORMAT(vouchdt,'%d-%m-%Y') AS vdt FROM todo WHERE done != 'Y' OR done IS NULL OR done = '' ORDER BY vouchdt DESC LIMIT 8");

// ---- Alerts & action items (built from data we've already verified above) ----
$alerts = [];
if ($overdueCount > 0) {
    $alerts[] = ['danger', "$overdueCount customer(s) overdue - " . inr($overdueTotal) . " outstanding after departure"];
}
if ($receivableCount > 0) {
    $alerts[] = ['amber', "$receivableCount customer(s) with pending dues - " . inr($receivableTotal) . " total receivable"];
}
if ($passportExpiring > 0) {
    $alerts[] = ['amber', "$passportExpiring passport(s) expiring within 30 days"];
}
if ($missVisa > 0) {
    $alerts[] = ['amber', "$missVisa pilgrim(s) with visa not yet received"];
}
if ($docIncomplete > 0) {
    $alerts[] = ['amber', "$docIncomplete pilgrim(s) with incomplete documents"];
}
if ($dep7 > 0) {
    $alerts[] = ['info', "$dep7 group(s) departing within the next 7 days"];
}
if (count($alerts) == 0) {
    $alerts[] = ['ok', "No outstanding alerts - everything looks current"];
}

// ---- Quick report links: [Label, file, icon] ----
$quickLinks = [
    'Accounts'   => [
        ['General Ledger', 'ledger.php', 'bi-journal-text'],
        ['Bank Book', 'bankbook.php?para=B', 'bi-bank'],
        ['Cash Book', 'bankbook.php?para=C&forac=M', 'bi-cash-coin'],
        ['Expense Register', 'expreg.php?para=M', 'bi-receipt-cutoff'],
        ['Bill Register', 'billreg.php?mode=last&para=D', 'bi-file-earmark-text'],
        ['Payment Received Register', 'payreg.php', 'bi-credit-card'],
        ['Outstanding (Final Amount)', 'register.php?para=FA', 'bi-hourglass-split'],
        ['Revenue Register', 'register.php?para=RV', 'bi-graph-up-arrow'],
    ],
    'Haj / Umrah' => [
        ['Main Summary Report', 'report.php?para=MS', 'bi-bar-chart'],
        ['Main Detail Report', 'report.php?para=MD', 'bi-list-columns'],
        ['Class Report', 'report.php?para=CS', 'bi-diagram-3'],
        ['Agent-wise Class', 'report.php?para=AW', 'bi-people'],
        ['Name List', 'report.php?para=NR', 'bi-card-list'],
        ['Age-wise Register', 'register.php?para=AG', 'bi-person-lines-fill'],
        ['Passport Expiry Report', 'report.php?para=PER', 'bi-calendar-x'],
        ['Pax Document Verification', 'paxdocverifyrep.php', 'bi-patch-check'],
    ],
    'FIT'         => [
        ['FIT Quotation Register', 'fitquotreg.php', 'bi-file-earmark-spreadsheet'],
        ['Ticket Sale Register', 'tiktsalereg.php', 'bi-airplane'],
        ['Hotel Sale Register', 'hotelsalereg.php', 'bi-building'],
        ['Food Sale Register', 'foodsalereg.php', 'bi-cup-hot'],
        ['Laundry Sale Register', 'laundrysalereg.php', 'bi-basket'],
        ['Transport Sale Register', 'transpsalereg.php', 'bi-car-front'],
        ['Visa Sale Register', 'visasalereg.php', 'bi-passport'],
    ],
    'Masters'     => [
        ['Hotels', 'hotels.php?mode=last', 'bi-building-fill'],
        ['Customers', 'customer.php?mode=last', 'bi-person-badge'],
        ['Agents', 'agent.php?mode=last', 'bi-person-check'],
        ['Suppliers', 'supplier.php?mode=last', 'bi-truck'],
        ['Bank', 'bank.php?mode=last', 'bi-bank2'],
        ['Cash', 'cash.php?mode=last', 'bi-wallet2'],
    ],
];
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>HUTFIT - Owner Dashboard</title>
    <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Inter:300,400,500,600,700,900" />
    <link href="assets/css/nucleo-icons.css" rel="stylesheet" />
    <link href="assets/css/nucleo-svg.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@24,400,0,0" />
    <link id="pagestyle" href="assets/css/material-dashboard.css?v=3.2.0" rel="stylesheet" />
    <script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
    <style>
        body { background: #f0f2f5; }
        .kpi-card { border: none; border-left: 4px solid #8392ab; transition: .25s; }
        .kpi-card:hover { transform: translateY(-4px); box-shadow: 0 10px 24px rgba(0,0,0,.08); }
        .kpi-card .kpi-icon { font-size: 28px; opacity: .85; }
        .kpi-value { font-size: 1.4rem; font-weight: 700; margin: 0; }
        .kpi-label { font-size: .73rem; text-transform: uppercase; letter-spacing: .03em; color: #6c757d; margin-bottom: 2px; }
        .kpi-foot { font-size: .72rem; color: #8392ab; margin-top: 2px; }
        .section-title { font-weight: 700; font-size: 1rem; margin: 18px 0 10px 4px; color: #344767; }
        .quick-link-card { display: block; text-decoration: none; color: #344767; background: #fff; border-radius: 10px; padding: 14px 10px; text-align: center; border: 1px solid #e9ecef; transition: .2s; height: 100%; }
        .quick-link-card:hover { background: #344767; color: #fff; transform: translateY(-3px); }
        .quick-link-card i { font-size: 22px; display: block; margin-bottom: 6px; }
        .quick-link-card span { font-size: .78rem; font-weight: 600; }
        .group-tab-pane { display: none; }
        .group-tab-pane.active { display: flex; }
        .table-compact th, .table-compact td { font-size: .82rem; padding: .45rem .6rem; }
        .filter-bar { background: #fff; border-radius: 10px; padding: 10px 14px; border: 1px solid #e9ecef; }
        .preset-btn { font-size: .72rem; padding: 4px 10px; border-radius: 14px; border: 1px solid #dee2e6; background: #fff; color: #344767; cursor: pointer; }
        .preset-btn:hover { background: #344767; color: #fff; }
        .bar-row { display: flex; align-items: center; gap: 8px; margin-bottom: 7px; }
        .bar-label { font-size: 12px; color: #6c757d; width: 110px; flex-shrink: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
        .bar-track { flex: 1; height: 8px; background: #f0f2f5; border-radius: 4px; overflow: hidden; }
        .bar-fill { height: 100%; border-radius: 4px; }
        .bar-val { font-size: 11px; color: #6c757d; width: 32px; text-align: right; flex-shrink: 0; }
        .alert-row { display: flex; align-items: center; gap: 10px; padding: 8px 0; border-bottom: 1px solid #f0f2f5; font-size: 12.5px; }
        .alert-row:last-child { border-bottom: none; }
        .alert-icon { width: 24px; height: 24px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 12px; flex-shrink: 0; color: #fff; }
        .forecast-row { display: flex; justify-content: space-between; align-items: center; padding: 8px 0; border-bottom: 1px solid #f0f2f5; font-size: 13px; }
        .forecast-row:last-child { border-bottom: none; }
    </style>
</head>

<body class="g-sidenav-show bg-gray-100">
    <main class="main-content position-relative max-height-vh-100 h-100 border-radius-lg">
        <div class="container-fluid py-3">

            <!-- HEADER -->
            <div class="row mb-3">
                <div class="col-md-5">
                    <h4 class="mb-0" style="color:#344767;font-weight:800;"><i class="bi bi-speedometer2"></i> Owner Dashboard</h4>
                    <p class="text-sm text-secondary mb-0">Welcome <?= htmlspecialchars($username) ?> &middot; <?= date("d M Y, l") ?></p>
                </div>
                <div class="col-md-7 mt-2 mt-md-0">
                    <form method="get" class="filter-bar d-flex flex-wrap align-items-center gap-2" id="filterForm">
                        <label class="text-xs text-secondary mb-0">Tour</label>
                        <select name="tour" id="tourSelect" class="form-control form-control-sm" style="width:200px;">
                            <option value="">— All Tours —</option>
                            <?php foreach ($tourList as $t): ?>
                                <option value="<?= htmlspecialchars($t['code']) ?>"
                                    data-from="<?= htmlspecialchars($t['fromdate']) ?>"
                                    data-to="<?= htmlspecialchars($t['todate']) ?>"
                                    <?= $tourFilter === $t['code'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($t['code']) ?> &mdash; <?= htmlspecialchars($t['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <label class="text-xs text-secondary mb-0">From</label>
                        <input type="date" name="from" id="fromInput" value="<?= htmlspecialchars($fromdt) ?>" class="form-control form-control-sm" style="width:140px;">
                        <label class="text-xs text-secondary mb-0">To</label>
                        <input type="date" name="to" id="toInput" value="<?= htmlspecialchars($todt) ?>" class="form-control form-control-sm" style="width:140px;">
                        <button type="submit" class="btn btn-dark btn-sm mb-0">Apply</button>
                    </form>
                </div>
            </div>

            <!-- CLASS BREAKDOWN (shown only when a tour is selected) -->
            <?php if ($tourFilter !== '' && count($classBreakdown) > 0):
                $maxClassPax = max(array_column($classBreakdown, 'pax'));
                $tourName = '';
                foreach ($tourList as $t) { if ($t['code'] === $tourFilter) { $tourName = $t['name']; break; } }
            ?>
            <div class="row mb-3">
                <div class="col-12">
                    <div class="card" style="border-left:4px solid #5e72e4;">
                        <div class="card-body py-2 px-3">
                            <h6 class="mb-2" style="color:#344767;font-weight:700;">
                                <i class="bi bi-diagram-3"></i> Tour <?= htmlspecialchars($tourFilter) ?> &mdash; <?= htmlspecialchars($tourName) ?> &mdash; Class-wise Breakdown
                            </h6>
                            <div class="row">
                                <?php foreach ($classBreakdown as $cl):
                                    $cpct = $maxClassPax > 0 ? round(($cl['pax'] / $maxClassPax) * 100) : 0;
                                    $clabel = $cl['batchno'] !== '' ? $cl['batchno'] : '(No Class)';
                                ?>
                                <div class="col-xl-3 col-md-4 col-sm-6 mb-2">
                                    <div class="d-flex justify-content-between mb-1">
                                        <span style="font-size:12px;font-weight:600;color:#344767;"><?= htmlspecialchars($clabel) ?></span>
                                        <span style="font-size:11px;color:#6c757d;"><?= (int)$cl['pax'] ?> pax &middot; <?= inr($cl['rev']) ?></span>
                                    </div>
                                    <div class="bar-track">
                                        <div class="bar-fill" style="width:<?= $cpct ?>%;background:#5e72e4;height:10px;border-radius:5px;"></div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <!-- REVENUE KPI ROW -->
            <div class="row">
                <div class="col-xl-3 col-sm-6 mb-4">
                    <div class="card kpi-card" style="border-left-color:#2dce89;">
                        <div class="card-body py-3 px-3 d-flex justify-content-between align-items-center">
                            <div>
                                <p class="kpi-label mb-1">Gross Revenue (Period)</p>
                                <p class="kpi-value"><?= inr($grossRevenue) ?></p>
                            </div>
                            <i class="bi bi-cash-stack kpi-icon" style="color:#2dce89;"></i>
                        </div>
                    </div>
                </div>
                <div class="col-xl-3 col-sm-6 mb-4">
                    <div class="card kpi-card" style="border-left-color:#5e72e4;">
                        <div class="card-body py-3 px-3 d-flex justify-content-between align-items-center">
                            <div>
                                <p class="kpi-label mb-1">Haj / Umrah Revenue</p>
                                <p class="kpi-value"><?= inr($hajRevenue) ?></p>
                            </div>
                            <i class="bi bi-building-check kpi-icon" style="color:#5e72e4;"></i>
                        </div>
                    </div>
                </div>
                <div class="col-xl-3 col-sm-6 mb-4">
                    <div class="card kpi-card" style="border-left-color:#fb6340;">
                        <div class="card-body py-3 px-3 d-flex justify-content-between align-items-center">
                            <div>
                                <p class="kpi-label mb-1">FIT Revenue</p>
                                <p class="kpi-value"><?= inr($fitRevenue) ?></p>
                            </div>
                            <i class="bi bi-suitcase-lg kpi-icon" style="color:#fb6340;"></i>
                        </div>
                    </div>
                </div>
                <div class="col-xl-3 col-sm-6 mb-4">
                    <div class="card kpi-card" style="border-left-color:#f5365c;">
                        <div class="card-body py-3 px-3 d-flex justify-content-between align-items-center">
                            <div>
                                <p class="kpi-label mb-1">Expense (Period)</p>
                                <p class="kpi-value"><?= inr($totalExpensePeriod) ?></p>
                            </div>
                            <i class="bi bi-receipt-cutoff kpi-icon" style="color:#f5365c;"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- ACCOUNTS / FINANCE ROW -->
            <!-- <div class="section-title"><i class="bi bi-bank"></i> Accounts &amp; Finance (Live)</div> -->
            <!-- <div class="row">
                <div class="col-xl-3 col-sm-6 mb-3">
                    <div class="card kpi-card" style="border-left-color:#11cdef;">
                        <div class="card-body py-2 px-3">
                            <p class="kpi-label mb-1">Bank + Cash Balance</p>
                            <p class="kpi-value" style="font-size:1.15rem;"><?= inr($bankCashBalance) ?></p>
                        </div>
                    </div>
                </div>
                <div class="col-xl-3 col-sm-6 mb-3">
                    <div class="card kpi-card" style="border-left-color:#fbb140;">
                        <div class="card-body py-2 px-3">
                            <p class="kpi-label mb-1">Outstanding Receivable</p>
                            <p class="kpi-value" style="font-size:1.15rem;"><?= inr($receivableTotal) ?></p>
                            <p class="kpi-foot"><?= (int)$receivableCount ?> customer(s) with dues</p>
                        </div>
                    </div>
                </div>
                <div class="col-xl-3 col-sm-6 mb-3">
                    <div class="card kpi-card" style="border-left-color:#f5365c;">
                        <div class="card-body py-2 px-3">
                            <p class="kpi-label mb-1">Overdue (Post-Departure)</p>
                            <p class="kpi-value" style="font-size:1.15rem;"><?= inr($overdueTotal) ?></p>
                            <p class="kpi-foot"><?= (int)$overdueCount ?> customer(s) overdue</p>
                        </div>
                    </div>
                </div>
                <div class="col-xl-3 col-sm-6 mb-3">
                    <div class="card kpi-card" style="border-left-color:#8898aa;">
                        <div class="card-body py-2 px-3">
                            <p class="kpi-label mb-1">Payable to Suppliers</p>
                            <p class="kpi-value" style="font-size:1.15rem;"><?= inr($payableTotal) ?></p>
                            <p class="kpi-foot"><?= (int)$payableCount ?> supplier(s) outstanding</p>
                        </div>
                    </div>
                </div>
            </div> -->

            <!-- BUSINESS SNAPSHOT ROW -->
            <div class="section-title">Business Snapshot (All-time)</div>
            <div class="row">
                <?php
                $snapshot = [
                    ['Active Bookings (Tour-wise)', $totBookings, 'bi-journal-check', '#11cdef'],
                    ['Cancelled Bookings (Tour-wise)', $totCancelled, 'bi-x-circle', '#8898aa'],
                    ['FIT Invoices', $totFitInv, 'bi-receipt', '#fb6340'],
                    ['Customers', $totCustomers, 'bi-person-badge', '#2dce89'],
                    ['Agents', $totAgents, 'bi-person-check', '#5e72e4'],
                    ['Suppliers', $totSuppliers, 'bi-truck', '#f5365c'],
                    ['Bank Accounts', $totBanks, 'bi-bank', '#11cdef'],
                    ['Hotels Onboarded', $totHotels, 'bi-buildings', '#fbb140'],
                ];
                foreach ($snapshot as $s) {
                    echo '<div class="col-xl-3 col-md-6 mb-3">
                            <div class="card kpi-card" style="border-left-color:' . $s[3] . ';">
                                <div class="card-body py-2 px-3 d-flex justify-content-between align-items-center">
                                    <div>
                                        <p class="kpi-label mb-1">' . $s[0] . '</p>
                                        <p class="kpi-value">' . (int)$s[1] . '</p>
                                    </div>
                                    <i class="bi ' . $s[2] . ' kpi-icon" style="color:' . $s[3] . ';"></i>
                                </div>
                            </div>
                          </div>';
                }
                ?>
            </div>

            <!-- FIT SERVICE BREAKDOWN ROW -->
            <div class="section-title">FIT Service-wise Revenue (Selected Period)</div>
            <div class="row">
                <?php
                $services = [
                    ['Ticket & Airline', $tiktAmt, 'bi-airplane', '#36a2eb'],
                    ['Hotel', $hotelAmt, 'bi-building', '#ffce56'],
                    ['Food', $foodAmt, 'bi-cup-hot', '#4bc0c0'],
                    ['Laundry', $laundAmt, 'bi-basket', '#9966ff'],
                    ['Transportation', $transAmt, 'bi-car-front', '#ff9f40'],
                    ['Visa', $visaAmt, 'bi-passport', '#ff6384'],
                ];
                foreach ($services as $sv) {
                    echo '<div class="col-xl-2 col-md-4 col-sm-6 mb-3">
                            <div class="card kpi-card" style="border-left-color:' . $sv[3] . ';">
                                <div class="card-body py-2 px-3">
                                    <p class="kpi-label mb-1"><i class="bi ' . $sv[2] . '"></i> ' . $sv[0] . '</p>
                                    <p class="kpi-value" style="font-size:1.1rem;">' . inr($sv[1]) . '</p>
                                </div>
                            </div>
                          </div>';
                }
                ?>
            </div>

            <!-- CHARTS ROW -->
            <div class="row mb-2">
                <div class="col-12 mb-4">
                    <div class="card">
                        <div class="card-header pb-0 d-flex justify-content-between align-items-center">
                            <h6 class="mb-0">Monthly Revenue &mdash; FIT vs Haj/Umrah</h6>
                            <form method="get" class="d-flex align-items-center">
                                <input type="hidden" name="tour" value="<?= htmlspecialchars($tourFilter) ?>">
                                <?php if ($tourFilter === ''): ?>
                                    <input type="hidden" name="from" value="<?= htmlspecialchars($fromdt) ?>">
                                    <input type="hidden" name="to" value="<?= htmlspecialchars($todt) ?>">
                                <?php endif; ?>
                                <select name="year" class="form-control form-control-sm" style="width:auto;" onchange="this.form.submit()">
                                    <?php for ($y = date("Y") + 1; $y >= date("Y") - 4; $y--) { ?>
                                        <option value="<?= $y ?>" <?= $y == $chartyear ? 'selected' : '' ?>><?= $y ?></option>
                                    <?php } ?>
                                </select>
                            </form>
                        </div>
                        <div class="card-body">
                            <canvas id="monthChart" height="70"></canvas>
                        </div>
                    </div>
                </div>
            </div>

            <!-- TREND + FIT REVENUE SPLIT ROW -->
            <div class="row mb-2">
                <div class="col-lg-6 mb-4">
                    <div class="card h-100">
                        <div class="card-header pb-0"><h6 class="mb-0">Bookings Trend &mdash; Last 6 Months</h6></div>
                        <div class="card-body">
                            <canvas id="trendChart" height="120"></canvas>
                        </div>
                    </div>
                </div>
                <div class="col-lg-6 mb-4">
                    <div class="card h-100">
                        <div class="card-header pb-0"><h6 class="mb-0">FIT Revenue Split (Period)</h6></div>
                        <div class="card-body">
                            <?php if ($fitRevenue > 0):
                                $fitServices = [
                                    ['Ticket & Airline', $tiktAmt, '#36a2eb'],
                                    ['Hotel',            $hotelAmt, '#ffce56'],
                                    ['Food',             $foodAmt,  '#4bc0c0'],
                                    ['Laundry',          $laundAmt, '#9966ff'],
                                    ['Transportation',   $transAmt, '#ff9f40'],
                                    ['Visa',             $visaAmt,  '#ff6384'],
                                ];
                            ?>
                            <div class="row align-items-center">
                                <div class="col-5 d-flex align-items-center justify-content-center">
                                    <canvas id="fitSplitChart" height="200"></canvas>
                                </div>
                                <div class="col-7">
                                    <?php foreach ($fitServices as $fs):
                                        $pct = $fitRevenue > 0 ? round(($fs[1] / $fitRevenue) * 100) : 0;
                                    ?>
                                    <div class="bar-row">
                                        <div class="bar-label"><?= $fs[0] ?></div>
                                        <div class="bar-track"><div class="bar-fill" style="width:<?= $pct ?>%;background:<?= $fs[2] ?>;"></div></div>
                                        <div class="bar-val"><?= $pct ?>%</div>
                                    </div>
                                    <?php endforeach; ?>
                                    <p class="text-xs text-secondary mt-2 mb-0">Total FIT: <?= inr($fitRevenue) ?></p>
                                </div>
                            </div>
                            <?php else: ?>
                                <div class="text-center py-5">
                                    <i class="bi bi-pie-chart" style="font-size:44px;color:#dee2e6;"></i>
                                    <p class="text-secondary mt-2 mb-0" style="font-size:.8rem;">No FIT revenue for selected period</p>
                                    <p class="text-secondary mb-0" style="font-size:.75rem;">Try selecting a wider date range</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- FORECAST + ALERTS ROW -->
            <div class="row mb-2">
                <div class="col-lg-7 mb-4">
                    <div class="card h-100">
                        <div class="card-header pb-0">
                            <h6 class="mb-0">Revenue Forecast &mdash; Next 6 Months</h6>
                            <p class="text-xs text-secondary mb-0">Confirmed bookings departing in upcoming months (not a statistical projection)</p>
                        </div>
                        <div class="card-body">
                            <canvas id="forecastChart" height="110"></canvas>
                        </div>
                    </div>
                </div>
                <div class="col-lg-5 mb-4">
                    <div class="card h-100">
                        <div class="card-header pb-0"><h6 class="mb-0">Alerts &amp; Action Items</h6></div>
                        <div class="card-body">
                            <?php
                            $iconMap = [
                                'danger' => ['bg' => '#A32D2D', 'icon' => '!'],
                                'amber'  => ['bg' => '#BA7517', 'icon' => '!'],
                                'info'   => ['bg' => '#185FA5', 'icon' => 'i'],
                                'ok'     => ['bg' => '#3B6D11', 'icon' => '✓'],
                            ];
                            foreach ($alerts as $al) {
                                $style = $iconMap[$al[0]];
                                echo '<div class="alert-row">
                                        <div class="alert-icon" style="background:' . $style['bg'] . ';">' . $style['icon'] . '</div>
                                        <div>' . htmlspecialchars($al[1]) . '</div>
                                      </div>';
                            }
                            ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- OPERATIONAL TABLES ROW -->
            <div class="row mb-2">
                <div class="col-lg-6 mb-4">
                    <div class="card h-100">
                        <div class="card-header pb-0"><h6 class="mb-0"><i class="bi bi-airplane-engines"></i> Upcoming Departures (30 days)</h6></div>
                        <div class="card-body p-2">
                            <div class="table-responsive">
                                <table class="table table-compact mb-0">
                                    <thead><tr><th>Voucher</th><th>Haji</th><th>Date</th></tr></thead>
                                    <tbody>
                                        <?php if (count($upcomingDep) == 0) { ?>
                                            <tr><td colspan="3" class="text-center text-secondary">No upcoming departures</td></tr>
                                        <?php } ?>
                                        <?php foreach ($upcomingDep as $d) { ?>
                                            <tr>
                                                <td><?= htmlspecialchars($d['vouchno']) ?></td>
                                                <td><?= htmlspecialchars($d['haji']) ?></td>
                                                <td><?= htmlspecialchars($d['depdt']) ?></td>
                                            </tr>
                                        <?php } ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-lg-6 mb-4">
                    <div class="card h-100">
                        <div class="card-header pb-0"><h6 class="mb-0"><i class="bi bi-journal-plus"></i> Recent Haj/Umrah Bookings</h6></div>
                        <div class="card-body p-2">
                            <div class="table-responsive">
                                <table class="table table-compact mb-0">
                                    <thead><tr><th>Voucher</th><th>Haji</th><th>Amount</th></tr></thead>
                                    <tbody>
                                        <?php if (count($recentBookings) == 0) { ?>
                                            <tr><td colspan="3" class="text-center text-secondary">No bookings found</td></tr>
                                        <?php } ?>
                                        <?php foreach ($recentBookings as $b) { ?>
                                            <tr>
                                                <td><?= htmlspecialchars($b['vouchno']) ?></td>
                                                <td><?= htmlspecialchars($b['haji']) ?></td>
                                                <td><?= inr($b['netamt']) ?></td>
                                            </tr>
                                        <?php } ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- Pending To-Do Tasks panel removed per owner request -->
            </div>

            <!-- QUICK REPORTS HUB -->
            <!-- <div class="section-title"><i class="bi bi-grid-3x3-gap"></i> Reports & Accounts Hub</div>
            <ul class="nav nav-pills mb-3" id="grpTabs">
                <?php $first = true; foreach ($quickLinks as $grp => $items) { ?>
                    <li class="nav-item">
                        <a class="nav-link <?= $first ? 'active' : '' ?>" href="#" data-target="grp-<?= preg_replace('/[^a-zA-Z]/', '', $grp) ?>" onclick="showGrp(this);return false;" style="<?= $first ? 'background:#344767;color:#fff;' : 'color:#344767;' ?>"><?= $grp ?></a>
                    </li>
                    <?php $first = false; ?>
                <?php } ?>
            </ul>
            <div class="row mb-4">
                <?php $first = true; foreach ($quickLinks as $grp => $items) { ?>
                    <div class="group-tab-pane <?= $first ? 'active' : '' ?>" id="grp-<?= preg_replace('/[^a-zA-Z]/', '', $grp) ?>" style="display:<?= $first ? 'flex' : 'none' ?>;flex-wrap:wrap;width:100%;">
                        <?php foreach ($items as $it) { ?>
                            <div class="col-xl-2 col-md-3 col-sm-4 col-6 mb-3">
                                <a href="<?= $it[1] ?>" class="quick-link-card">
                                    <i class="bi <?= $it[2] ?>"></i>
                                    <span><?= $it[0] ?></span>
                                </a>
                            </div>
                        <?php } ?>
                    </div>
                    <?php $first = false; ?>
                <?php } ?>
            </div> -->

        </div>
    </main>

    <script>
        function showGrp(el) {
            document.querySelectorAll('#grpTabs .nav-link').forEach(function (n) {
                n.classList.remove('active');
                n.style.background = 'transparent';
                n.style.color = '#344767';
            });
            el.classList.add('active');
            el.style.background = '#344767';
            el.style.color = '#fff';
            document.querySelectorAll('.group-tab-pane').forEach(function (p) { p.style.display = 'none'; });
            document.getElementById(el.getAttribute('data-target')).style.display = 'flex';
        }

        const monthLabels = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
        const fitData = <?= json_encode(array_values($fitByMonth)) ?>;
        const hajData = <?= json_encode(array_values($hajByMonth)) ?>;

        // Monthly Revenue bar chart
        new Chart(document.getElementById('monthChart').getContext('2d'), {
            type: 'bar',
            data: {
                labels: monthLabels,
                datasets: [
                    { label: 'FIT', data: fitData, backgroundColor: 'rgba(255,99,132,0.6)', borderColor: '#ff6384', borderWidth: 1 },
                    { label: 'Haj / Umrah', data: hajData, backgroundColor: 'rgba(54,162,235,0.6)', borderColor: '#36a2eb', borderWidth: 1 }
                ]
            },
            options: {
                responsive: true,
                legend: { display: true, position: 'top' },
                scales: { yAxes: [{ ticks: { beginAtZero: true } }] }
            }
        });

        // FIT Revenue Split doughnut - only rendered when there is data
        <?php if ($fitRevenue > 0): ?>
        new Chart(document.getElementById('fitSplitChart').getContext('2d'), {
            type: 'doughnut',
            data: {
                labels: ['Ticket & Airline', 'Hotel', 'Food', 'Laundry', 'Transportation', 'Visa'],
                datasets: [{
                    data: [<?= $tiktAmt ?>, <?= $hotelAmt ?>, <?= $foodAmt ?>, <?= $laundAmt ?>, <?= $transAmt ?>, <?= $visaAmt ?>],
                    backgroundColor: ['#36a2eb', '#ffce56', '#4bc0c0', '#9966ff', '#ff9f40', '#ff6384']
                }]
            },
            options: {
                responsive: true,
                legend: { position: 'bottom', labels: { boxWidth: 12, fontSize: 10 } }
            }
        });
        <?php endif; ?>

        // Bookings Trend line chart
        new Chart(document.getElementById('trendChart').getContext('2d'), {
            type: 'line',
            data: {
                labels: <?= json_encode($trendLabels) ?>,
                datasets: [
                    { label: 'Haj/Umrah Bookings', data: <?= json_encode($trendHaj) ?>, borderColor: '#378ADD', backgroundColor: 'rgba(55,138,221,0.12)', fill: true, lineTension: 0.3, pointRadius: 4 },
                    { label: 'FIT Invoices',        data: <?= json_encode($trendFit) ?>, borderColor: '#1D9E75', backgroundColor: 'rgba(29,158,117,0.12)', fill: true, lineTension: 0.3, pointRadius: 4 }
                ]
            },
            options: {
                responsive: true,
                legend: { display: true, position: 'top' },
                scales: { yAxes: [{ ticks: { beginAtZero: true } }] }
            }
        });

        // Revenue Forecast bar chart - next 6 months
        new Chart(document.getElementById('forecastChart').getContext('2d'), {
            type: 'bar',
            data: {
                labels: <?= json_encode($forecastLabels) ?>,
                datasets: [{
                    label: 'Forecasted Revenue (₹)',
                    data: <?= json_encode($forecastAmt) ?>,
                    backgroundColor: [
                        'rgba(94,114,228,0.7)', 'rgba(94,114,228,0.6)', 'rgba(94,114,228,0.5)',
                        'rgba(94,114,228,0.4)', 'rgba(94,114,228,0.35)', 'rgba(94,114,228,0.3)'
                    ],
                    borderColor: '#5e72e4',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                legend: { display: false },
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: true,
                            callback: function(v) {
                                if (v >= 100000) return '₹' + (v/100000).toFixed(1) + 'L';
                                if (v >= 1000)   return '₹' + (v/1000).toFixed(0) + 'K';
                                return '₹' + v;
                            }
                        }
                    }],
                    xAxes: [{ ticks: { fontSize: 11 } }]
                },
                tooltips: {
                    callbacks: {
                        label: function(ti) {
                            var v = ti.yLabel;
                            return ' ₹ ' + v.toLocaleString('en-IN');
                        }
                    }
                }
            }
        });

        // Tour select: auto-fill dates from master, then submit
        document.getElementById('tourSelect').addEventListener('change', function () {
            var opt = this.options[this.selectedIndex];
            var from = opt.getAttribute('data-from');
            var to   = opt.getAttribute('data-to');
            if (from && from !== '0000-00-00') {
                document.getElementById('fromInput').value = from;
                document.getElementById('toInput').value   = (to && to !== '0000-00-00') ? to : '';
            } else {
                document.getElementById('fromInput').value = '';
                document.getElementById('toInput').value   = '';
            }
            this.closest('form').submit();
        });
    </script>
</body>

</html>
