<?php
/* InventoryDashboard.php - Enhanced Inventory Dashboard with React Ant Design Styling */
error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity = 0;
include('includes/session.inc');
$Title = _('Inventory Dashboard');
include('includes/newheader.php');
$userid = $_SESSION['UserID'];
?>
<!-- ══════════════════════════════════════════════════════════════ -->
<!-- Loading Modal - renders immediately while DB queries run      -->
<!-- ══════════════════════════════════════════════════════════════ -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/jszip-2.5.0/dt-1.10.16/b-1.5.1/b-flash-1.5.1/b-html5-1.5.1/b-print-1.5.1/datatables.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.5.1/css/buttons.dataTables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.flash.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.print.min.js"></script>

<div id="dash-loading-modal" style="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(255,255,255,0.95);z-index:9999;display:flex;align-items:center;justify-content:center;">
  <div style="text-align:center;">
    <div style="width:48px;height:48px;border:4px solid #E6F7F8;border-top:4px solid #2AABB3;border-radius:50%;animation:dbspin 0.8s linear infinite;margin:0 auto 16px;"></div>
    <div style="font-family:'Poppins',sans-serif;color:#1F2937;font-size:15px;font-weight:500;">Loading Inventory Dashboard...</div>
    <div id="dash-load-timer" style="font-family:'Poppins',sans-serif;color:#6B7280;font-size:12px;margin-top:6px;">0s</div>
  </div>
</div>
<style>@keyframes dbspin{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style>
<script>(function(){var s=0;var t=setInterval(function(){s++;var el=document.getElementById('dash-load-timer');if(el)el.textContent=s+'s';},1000);window._dashTimer=t;})();</script>
<?php if(function_exists('ob_flush')){ob_flush();}flush(); ?>

<?php
// ── Direct DB connection ──
$dbc = mysqli_connect('localhost','sooggoo','4Compassion*','evergreenint');
if(!$dbc){die('DB connection failed');}
mysqli_set_charset($dbc,'utf8');

$currentmonth = date('m');
$currentyear  = date('Y');
$monthName    = date('F Y');
$monthShort   = date('M');
$currentdate  = $currentyear.'-'.$currentmonth.'-01';
$currentdate2 = $currentyear.'-'.$currentmonth.'-31';

// ═══════════════════════════════════════════════════════════════
// KPI QUERIES
// ═══════════════════════════════════════════════════════════════

// KPI 1: Total Items Dispatched This Month
$sql = "SELECT COALESCE(SUM(sri.quantity),0) AS total_qty, COUNT(DISTINCT sri.stockid) AS unique_items
        FROM stockrequestitems sri
        INNER JOIN stockrequest sr ON sr.dispatchid = sri.dispatchid
        WHERE sr.despatchdate BETWEEN '$currentdate' AND '$currentdate2'";
$r = mysqli_query($dbc,$sql);
$kpi = ($r) ? mysqli_fetch_assoc($r) : array('total_qty'=>0,'unique_items'=>0);
$totalQtyMonth   = (int)$kpi['total_qty'];
$uniqueItemsMonth = (int)$kpi['unique_items'];

// KPI 2: Total Stock Requests This Month
$sql = "SELECT COUNT(DISTINCT sr.dispatchid) AS cnt FROM stockrequest sr WHERE sr.despatchdate BETWEEN '$currentdate' AND '$currentdate2'";
$r = mysqli_query($dbc,$sql);
$row = ($r) ? mysqli_fetch_assoc($r) : array('cnt'=>0);
$totalRequests = (int)$row['cnt'];

// KPI 3: Departments Served
$sql = "SELECT COUNT(DISTINCT sr.departmentid) AS cnt FROM stockrequest sr WHERE sr.despatchdate BETWEEN '$currentdate' AND '$currentdate2'";
$r = mysqli_query($dbc,$sql);
$row = ($r) ? mysqli_fetch_assoc($r) : array('cnt'=>0);
$deptServed = (int)$row['cnt'];

// KPI 4: Week qty
$sql = "SELECT COALESCE(SUM(sri.quantity),0) AS wq FROM stockrequestitems sri INNER JOIN stockrequest sr ON sr.dispatchid=sri.dispatchid WHERE sr.despatchdate >= DATE(NOW()-INTERVAL 7 DAY)";
$r = mysqli_query($dbc,$sql);
$row = ($r) ? mysqli_fetch_assoc($r) : array('wq'=>0);
$weekQty = (int)$row['wq'];

// KPI 5: Security Items This Month
$sql = "SELECT COALESCE(SUM(sri.quantity),0) AS sq FROM stockrequestitems sri INNER JOIN stockmaster sm ON sm.stockid=sri.stockid INNER JOIN stockrequest sr ON sr.dispatchid=sri.dispatchid WHERE sm.categoryid='SEC' AND sr.despatchdate BETWEEN '$currentdate' AND '$currentdate2'";
$r = mysqli_query($dbc,$sql);
$row = ($r) ? mysqli_fetch_assoc($r) : array('sq'=>0);
$secQty = (int)$row['sq'];

// KPI 6: Fire Items This Month
$sql = "SELECT COALESCE(SUM(sri.quantity),0) AS fq FROM stockrequestitems sri INNER JOIN stockmaster sm ON sm.stockid=sri.stockid INNER JOIN stockrequest sr ON sr.dispatchid=sri.dispatchid WHERE sm.categoryid='FIRE' AND sr.despatchdate BETWEEN '$currentdate' AND '$currentdate2'";
$r = mysqli_query($dbc,$sql);
$row = ($r) ? mysqli_fetch_assoc($r) : array('fq'=>0);
$fireQty = (int)$row['fq'];

// KPI 7: Average Items Per Request
$avgPerReq = ($totalRequests > 0) ? round($totalQtyMonth / $totalRequests, 1) : 0;

// KPI 8: Total Categories Active
$sql = "SELECT COUNT(DISTINCT sm.categoryid) AS cc FROM stockrequestitems sri INNER JOIN stockmaster sm ON sm.stockid=sri.stockid INNER JOIN stockrequest sr ON sr.dispatchid=sri.dispatchid WHERE sr.despatchdate BETWEEN '$currentdate' AND '$currentdate2'";
$r = mysqli_query($dbc,$sql);
$row = ($r) ? mysqli_fetch_assoc($r) : array('cc'=>0);
$activeCats = (int)$row['cc'];

// ═══════════════════════════════════════════════════════════════
// CHART DATA
// ═══════════════════════════════════════════════════════════════

// Chart 1: Top 10 Installs (Dept 9/10 + SEC)
$sql = "SELECT SUM(sri.quantity) AS qtydelivered, sm.description
        FROM stockrequestitems sri
        INNER JOIN stockmaster sm ON sm.stockid=sri.stockid
        INNER JOIN stockrequest sr ON sr.dispatchid=sri.dispatchid
        WHERE (sr.departmentid IN (9,10)) AND sm.categoryid='SEC'
        AND sr.despatchdate BETWEEN '$currentdate' AND '$currentdate2'
        GROUP BY sri.stockid ORDER BY qtydelivered DESC LIMIT 10";
$r = mysqli_query($dbc,$sql);
$installLabels=array(); $installData=array();
if($r){ while($row=mysqli_fetch_assoc($r)){ $installLabels[]=$row['description']; $installData[]=(int)$row['qtydelivered']; }}

// Chart 2: Top 10 Fire (Dept 6/7/8 + FIRE)
$sql = "SELECT SUM(sri.quantity) AS qtydelivered, sm.description
        FROM stockrequestitems sri
        INNER JOIN stockmaster sm ON sm.stockid=sri.stockid
        INNER JOIN stockrequest sr ON sr.dispatchid=sri.dispatchid
        WHERE (sr.departmentid IN (6,7,8)) AND sm.categoryid='FIRE'
        AND sr.despatchdate BETWEEN '$currentdate' AND '$currentdate2'
        GROUP BY sri.stockid ORDER BY qtydelivered DESC LIMIT 10";
$r = mysqli_query($dbc,$sql);
$fireLabels=array(); $fireData=array();
if($r){ while($row=mysqli_fetch_assoc($r)){ $fireLabels[]=$row['description']; $fireData[]=(int)$row['qtydelivered']; }}

// Chart 3: Department Breakdown (NEW - pie/doughnut)
$sql = "SELECT d.departmentname, COALESCE(SUM(sri.quantity),0) AS qty
        FROM stockrequestitems sri
        INNER JOIN stockrequest sr ON sr.dispatchid=sri.dispatchid
        INNER JOIN department d ON d.departmentid=sr.departmentid
        WHERE sr.despatchdate BETWEEN '$currentdate' AND '$currentdate2'
        GROUP BY sr.departmentid ORDER BY qty DESC LIMIT 8";
$r = mysqli_query($dbc,$sql);
$deptLabels=array(); $deptData=array();
if($r){ while($row=mysqli_fetch_assoc($r)){ $deptLabels[]=$row['departmentname']; $deptData[]=(int)$row['qty']; }}

// Chart 4: Category Breakdown (NEW - doughnut)
$sql = "SELECT sm.categoryid, COALESCE(SUM(sri.quantity),0) AS qty
        FROM stockrequestitems sri
        INNER JOIN stockmaster sm ON sm.stockid=sri.stockid
        INNER JOIN stockrequest sr ON sr.dispatchid=sri.dispatchid
        WHERE sr.despatchdate BETWEEN '$currentdate' AND '$currentdate2'
        GROUP BY sm.categoryid ORDER BY qty DESC LIMIT 10";
$r = mysqli_query($dbc,$sql);
$catLabels=array(); $catData=array();
if($r){ while($row=mysqli_fetch_assoc($r)){ $catLabels[]=$row['categoryid']; $catData[]=(int)$row['qty']; }}

// Chart 5: Stock On Hand by Location for SEC/FIRE items (from original query9)
$sql = "SELECT SUM(sri.quantity) AS qtydelivered, sm.description, sri.stockid
        FROM stockrequestitems sri
        INNER JOIN stockmaster sm ON sm.stockid=sri.stockid
        INNER JOIN stockrequest sr ON sr.dispatchid=sri.dispatchid
        WHERE (sm.categoryid='FIRE' OR sm.categoryid='SEC')
        AND sr.despatchdate BETWEEN '$currentdate' AND '$currentdate2'
        GROUP BY sri.stockid ORDER BY qtydelivered DESC LIMIT 15";
$r = mysqli_query($dbc,$sql);
$stockOnHand = array();
if($r){
    while($row=mysqli_fetch_assoc($r)){
        $sid = $row['stockid'];
        $entry = array('desc'=>$row['description'],'dispatched'=>(int)$row['qtydelivered'],'suva'=>0,'nadi'=>0,'north'=>0);
        // SUVA
        $r2 = mysqli_query($dbc,"SELECT quantity FROM locstock WHERE stockid='".mysqli_real_escape_string($dbc,$sid)."' AND loccode='SUVA'");
        if($r2 && $row2=mysqli_fetch_assoc($r2)){ $entry['suva']=(int)$row2['quantity']; }
        // NADI
        $r2 = mysqli_query($dbc,"SELECT quantity FROM locstock WHERE stockid='".mysqli_real_escape_string($dbc,$sid)."' AND loccode='NADI'");
        if($r2 && $row2=mysqli_fetch_assoc($r2)){ $entry['nadi']=(int)$row2['quantity']; }
        // NORTH
        $r2 = mysqli_query($dbc,"SELECT quantity FROM locstock WHERE stockid='".mysqli_real_escape_string($dbc,$sid)."' AND loccode='NORTH'");
        if($r2 && $row2=mysqli_fetch_assoc($r2)){ $entry['north']=(int)$row2['quantity']; }
        $stockOnHand[] = $entry;
    }
}

// Chart 6: Monthly Trend - Last 6 months (NEW)
$trendLabels=array(); $trendData=array();
for($i=5;$i>=0;$i--){
    $tm = date('m', strtotime("-$i months"));
    $ty = date('Y', strtotime("-$i months"));
    $tl = date('M Y', strtotime("-$i months"));
    $td1 = "$ty-$tm-01"; $td2 = "$ty-$tm-31";
    $sql = "SELECT COALESCE(SUM(sri.quantity),0) AS mq FROM stockrequestitems sri INNER JOIN stockrequest sr ON sr.dispatchid=sri.dispatchid WHERE sr.despatchdate BETWEEN '$td1' AND '$td2'";
    $r = mysqli_query($dbc,$sql);
    $row = ($r) ? mysqli_fetch_assoc($r) : array('mq'=>0);
    $trendLabels[] = $tl;
    $trendData[] = (int)$row['mq'];
}

// Chart 7: All-Time Top 30 SEC/FIRE Items (from original query10)
$sql = "SELECT SUM(sri.quantity) AS qtydelivered, sm.description
        FROM stockrequestitems sri
        INNER JOIN stockmaster sm ON sm.stockid=sri.stockid
        WHERE sm.categoryid IN ('FIRE','SEC')
        GROUP BY sri.stockid, sm.categoryid ORDER BY qtydelivered DESC LIMIT 20";
$r = mysqli_query($dbc,$sql);
$allTimeLabels=array(); $allTimeData=array();
if($r){ while($row=mysqli_fetch_assoc($r)){ $allTimeLabels[]=$row['description']; $allTimeData[]=(int)$row['qtydelivered']; }}

// Table 1: Top 100 Monthly
$sql = "SELECT sri.stockid, SUM(sri.quantity) AS qtydelivered, sm.description, d.departmentname, sm.categoryid
        FROM stockrequestitems sri
        INNER JOIN stockmaster sm ON sm.stockid=sri.stockid
        INNER JOIN stockrequest sr ON sr.dispatchid=sri.dispatchid
        INNER JOIN department d ON d.departmentid=sr.departmentid
        WHERE sr.despatchdate BETWEEN '$currentdate' AND '$currentdate2'
        GROUP BY sri.stockid ORDER BY qtydelivered DESC LIMIT 100";
$r_monthly = mysqli_query($dbc,$sql);
$monthlyRows = array();
if($r_monthly){ while($row=mysqli_fetch_assoc($r_monthly)){ $monthlyRows[]=$row; }}

// Table 2: Top 30 Weekly
$sql = "SELECT sri.stockid, SUM(sri.quantity) AS qtydelivered, sm.description, d.departmentname, sm.categoryid
        FROM stockrequestitems sri
        INNER JOIN stockmaster sm ON sm.stockid=sri.stockid
        INNER JOIN stockrequest sr ON sr.dispatchid=sri.dispatchid
        INNER JOIN department d ON d.departmentid=sr.departmentid
        WHERE sr.despatchdate >= DATE(NOW()-INTERVAL 7 DAY)
        GROUP BY sri.stockid ORDER BY qtydelivered DESC LIMIT 30";
$r_weekly = mysqli_query($dbc,$sql);
$weeklyRows = array();
if($r_weekly){ while($row=mysqli_fetch_assoc($r_weekly)){ $weeklyRows[]=$row; }}

// NEW: Top Requesting Departments This Month (for panel list)
$sql = "SELECT d.departmentname, COUNT(DISTINCT sr.dispatchid) AS req_count, COALESCE(SUM(sri.quantity),0) AS total_qty
        FROM stockrequest sr
        INNER JOIN department d ON d.departmentid=sr.departmentid
        INNER JOIN stockrequestitems sri ON sri.dispatchid=sr.dispatchid
        WHERE sr.despatchdate BETWEEN '$currentdate' AND '$currentdate2'
        GROUP BY sr.departmentid ORDER BY total_qty DESC LIMIT 8";
$r = mysqli_query($dbc,$sql);
$topDepts = array();
if($r){ while($row=mysqli_fetch_assoc($r)){ $topDepts[]=$row; }}

// NEW: Low Stock Alerts - SEC/FIRE items with total on hand < 10
$sql = "SELECT sm.stockid, sm.description, sm.categoryid,
        COALESCE(SUM(ls.quantity),0) AS total_onhand
        FROM stockmaster sm
        LEFT JOIN locstock ls ON ls.stockid=sm.stockid
        WHERE sm.categoryid IN ('SEC','FIRE')
        GROUP BY sm.stockid
        HAVING total_onhand < 10 AND total_onhand >= 0
        ORDER BY total_onhand ASC LIMIT 12";
$r = mysqli_query($dbc,$sql);
$lowStockAlerts = array();
if($r){ while($row=mysqli_fetch_assoc($r)){ $lowStockAlerts[]=$row; }}

mysqli_close($dbc);
?>

<!-- ══════════════════════════════════════════════════════════════ -->
<!-- DASHBOARD STYLES                                              -->
<!-- ══════════════════════════════════════════════════════════════ -->
<style>
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
:root{--primary:#2AABB3;--primary-dark:#1E8F96;--primary-darker:#187278;--primary-light:#E6F7F8;--success:#52C41A;--warning:#FAAD14;--danger:#FF4D4F;--info:#1890FF;--border:#E5E7EB;--text:#1F2937;--text-secondary:#6B7280;--bg-card:#FFFFFF;--shadow:0 1px 3px rgba(0,0,0,0.08);--shadow-md:0 4px 12px rgba(0,0,0,0.08);--radius:10px;}
*{box-sizing:border-box;}
.inv-dashboard{font-family:'Poppins',sans-serif;color:var(--text);padding:0;}

/* ── Gradient Banner ── */
.inv-banner{background:linear-gradient(135deg,var(--primary-darker) 0%,var(--primary) 50%,#35C4CD 100%);padding:28px 32px 22px;margin:-15px -15px 0 -15px;color:#fff;position:relative;overflow:hidden;}
.inv-banner::before{content:'';position:absolute;top:-40px;right:-40px;width:200px;height:200px;background:rgba(255,255,255,0.06);border-radius:50%;}
.inv-banner::after{content:'';position:absolute;bottom:-60px;left:30%;width:300px;height:300px;background:rgba(255,255,255,0.04);border-radius:50%;}
.inv-banner h2{margin:0 0 4px;font-size:22px;font-weight:600;position:relative;z-index:1;}
.inv-banner-sub{font-size:13px;opacity:0.85;position:relative;z-index:1;}
.inv-breadcrumb{display:flex;align-items:center;gap:8px;font-size:12px;opacity:0.75;margin-bottom:10px;position:relative;z-index:1;}
.inv-breadcrumb a{color:#fff;text-decoration:none;}
.inv-breadcrumb a:hover{text-decoration:underline;}

/* ── Toggle Button ── */
.dash-toggle-wrap{text-align:center;margin:0 -15px;position:relative;z-index:2;}
.dash-toggle{display:inline-flex;align-items:center;gap:6px;padding:7px 22px;background:var(--bg-card);border:1px solid var(--border);border-radius:0 0 20px 20px;cursor:pointer;font-family:'Poppins',sans-serif;font-size:12px;font-weight:500;color:var(--text-secondary);box-shadow:var(--shadow);transition:all 0.2s;}
.dash-toggle:hover{color:var(--primary);border-color:var(--primary);}
.dash-toggle i{transition:transform 0.3s;}
.dash-toggle.collapsed i{transform:rotate(180deg);}

/* ── Dashboard Container ── */
.inv-dash-content{padding:20px 0;transition:all 0.4s ease;}
.inv-dash-content.collapsed{max-height:0;overflow:hidden;padding:0;opacity:0;}

/* ── KPI Cards ── */
.inv-kpi-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:24px;}
.inv-kpi{background:var(--bg-card);border-radius:var(--radius);padding:18px 16px;box-shadow:var(--shadow);border-left:4px solid var(--primary);display:flex;align-items:center;gap:14px;transition:transform 0.2s,box-shadow 0.2s;}
.inv-kpi:hover{transform:translateY(-2px);box-shadow:var(--shadow-md);}
.inv-kpi-icon{width:44px;height:44px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:18px;flex-shrink:0;}
.inv-kpi-icon.teal{background:var(--primary-light);color:var(--primary-dark);}
.inv-kpi-icon.blue{background:#EBF5FF;color:var(--info);}
.inv-kpi-icon.green{background:#F0FFF4;color:var(--success);}
.inv-kpi-icon.orange{background:#FFF8E6;color:var(--warning);}
.inv-kpi-icon.red{background:#FFF1F0;color:var(--danger);}
.inv-kpi-icon.purple{background:#F3E8FF;color:#7C3AED;}
.inv-kpi-info{flex:1;min-width:0;}
.inv-kpi-val{font-size:22px;font-weight:700;color:var(--text);line-height:1.2;}
.inv-kpi-label{font-size:11px;color:var(--text-secondary);font-weight:500;text-transform:uppercase;letter-spacing:0.3px;margin-top:2px;}

/* ── Chart Panels ── */
.inv-chart-grid{display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:24px;}
.inv-chart-grid-3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:20px;margin-bottom:24px;}
.inv-panel{background:var(--bg-card);border-radius:var(--radius);box-shadow:var(--shadow);overflow:hidden;}
.inv-panel-head{padding:14px 18px 10px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;}
.inv-panel-head h3{margin:0;font-size:14px;font-weight:600;color:var(--text);}
.inv-panel-badge{font-size:10px;padding:3px 10px;border-radius:20px;font-weight:600;background:var(--primary-light);color:var(--primary-dark);}
.inv-panel-body{padding:16px 18px;}
.inv-chart-box{position:relative;height:280px;}
.inv-chart-box-sm{position:relative;height:220px;}

/* ── Panel List / Ranking ── */
.inv-rank-list{list-style:none;padding:0;margin:0;}
.inv-rank-list li{display:flex;align-items:center;gap:10px;padding:8px 0;border-bottom:1px solid #F3F4F6;}
.inv-rank-list li:last-child{border-bottom:none;}
.inv-rank-num{width:24px;height:24px;border-radius:50%;background:var(--primary-light);color:var(--primary-dark);font-size:11px;font-weight:700;display:flex;align-items:center;justify-content:center;flex-shrink:0;}
.inv-rank-name{flex:1;font-size:12px;color:var(--text);font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
.inv-rank-val{font-size:12px;font-weight:700;color:var(--text);}
.inv-rank-sub{font-size:10px;color:var(--text-secondary);margin-left:4px;}

/* ── Stock On Hand Table ── */
.inv-soh-table{width:100%;border-collapse:collapse;font-size:12px;}
.inv-soh-table th{background:#F9FAFB;color:var(--text-secondary);font-weight:600;text-transform:uppercase;font-size:10px;letter-spacing:0.5px;padding:10px 12px;text-align:left;border-bottom:2px solid var(--border);}
.inv-soh-table td{padding:9px 12px;border-bottom:1px solid #F3F4F6;color:var(--text);}
.inv-soh-table tr:hover td{background:#FAFBFC;}
.inv-soh-badge{display:inline-block;padding:2px 8px;border-radius:10px;font-size:10px;font-weight:600;}
.inv-soh-badge.ok{background:#F0FFF4;color:var(--success);}
.inv-soh-badge.warn{background:#FFF8E6;color:var(--warning);}
.inv-soh-badge.crit{background:#FFF1F0;color:var(--danger);}

/* ── Low Stock Alert Cards ── */
.inv-alert-row{display:flex;align-items:center;gap:10px;padding:8px 12px;border-radius:8px;margin-bottom:6px;font-size:12px;transition:background 0.2s;}
.inv-alert-row:hover{background:#F9FAFB;}
.inv-alert-dot{width:8px;height:8px;border-radius:50%;flex-shrink:0;}
.inv-alert-dot.red{background:var(--danger);}
.inv-alert-dot.orange{background:var(--warning);}
.inv-alert-dot.green{background:var(--success);}
.inv-alert-name{flex:1;font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
.inv-alert-cat{font-size:10px;padding:2px 6px;border-radius:4px;background:#F3F4F6;color:var(--text-secondary);font-weight:600;}
.inv-alert-qty{font-weight:700;min-width:40px;text-align:right;}

/* ── Section Divider ── */
.inv-section-title{font-size:16px;font-weight:600;color:var(--text);margin:28px 0 16px;padding-bottom:8px;border-bottom:2px solid var(--primary-light);display:flex;align-items:center;gap:10px;}
.inv-section-title i{color:var(--primary);font-size:18px;}

/* ── Data Tables Styling ── */
.inv-table-panel{background:var(--bg-card);border-radius:var(--radius);box-shadow:var(--shadow);padding:20px;margin-bottom:24px;}
.inv-table-panel h3{margin:0 0 16px;font-size:15px;font-weight:600;color:var(--text);display:flex;align-items:center;gap:8px;}
.inv-table-panel h3 i{color:var(--primary);}
.inv-table-panel .table{font-family:'Poppins',sans-serif;font-size:12px;}
.inv-table-panel .table thead th{background:linear-gradient(135deg,var(--primary-darker),var(--primary));color:#fff;font-weight:600;font-size:11px;text-transform:uppercase;letter-spacing:0.5px;padding:12px 14px;border:none;}
.inv-table-panel .table tbody td{padding:10px 14px;border-bottom:1px solid #F3F4F6;vertical-align:middle;}
.inv-table-panel .table tbody tr:hover td{background:var(--primary-light);}
.inv-table-panel .dataTables_wrapper .dt-buttons .dt-button{background:var(--primary)!important;color:#fff!important;border:none!important;border-radius:6px!important;padding:6px 16px!important;font-family:'Poppins',sans-serif!important;font-size:11px!important;font-weight:500!important;margin-right:6px!important;}
.inv-table-panel .dataTables_wrapper .dt-buttons .dt-button:hover{background:var(--primary-dark)!important;}

/* ── Responsive ── */
@media(max-width:1200px){.inv-kpi-grid{grid-template-columns:repeat(2,1fr);}.inv-chart-grid-3{grid-template-columns:1fr 1fr;}}
@media(max-width:768px){.inv-kpi-grid{grid-template-columns:1fr;}.inv-chart-grid{grid-template-columns:1fr;}.inv-chart-grid-3{grid-template-columns:1fr;}}
</style>

<div class="inv-dashboard">

<!-- ═══════════════════ GRADIENT BANNER ═══════════════════ -->
<div class="inv-banner">
    <div class="inv-breadcrumb">
        <a href="index.php"><i class="fa fa-home"></i> Home</a>
        <span>/</span>
        <a href="SelectProduct.php">Inventory</a>
        <span>/</span>
        <span>Dashboard</span>
    </div>
    <h2><i class="fa fa-boxes-stacked"></i> Inventory Dashboard</h2>
    <div class="inv-banner-sub"><i class="fa fa-calendar-alt"></i> <?php echo $monthName; ?> &nbsp;|&nbsp; <i class="fa fa-user"></i> <?php echo htmlspecialchars($userid); ?></div>
</div>

<!-- ═══════════════════ TOGGLE ═══════════════════ -->
<div class="dash-toggle-wrap">
    <button class="dash-toggle" id="invDashToggle" onclick="toggleInvDash()">
        <i class="fa fa-chevron-up"></i> <span>Hide Dashboard</span>
    </button>
</div>

<!-- ═══════════════════ COLLAPSIBLE DASHBOARD ═══════════════════ -->
<div class="inv-dash-content" id="invDashContent">

<!-- ── KPI ROW ── -->
<div class="inv-kpi-grid">
    <div class="inv-kpi">
        <div class="inv-kpi-icon teal"><i class="fa fa-cubes"></i></div>
        <div class="inv-kpi-info">
            <div class="inv-kpi-val"><?php echo number_format($totalQtyMonth); ?></div>
            <div class="inv-kpi-label">Items Dispatched (Month)</div>
        </div>
    </div>
    <div class="inv-kpi">
        <div class="inv-kpi-icon blue"><i class="fa fa-clipboard-list"></i></div>
        <div class="inv-kpi-info">
            <div class="inv-kpi-val"><?php echo number_format($totalRequests); ?></div>
            <div class="inv-kpi-label">Stock Requests</div>
        </div>
    </div>
    <div class="inv-kpi">
        <div class="inv-kpi-icon green"><i class="fa fa-boxes-packing"></i></div>
        <div class="inv-kpi-info">
            <div class="inv-kpi-val"><?php echo number_format($uniqueItemsMonth); ?></div>
            <div class="inv-kpi-label">Unique Items Moved</div>
        </div>
    </div>
    <div class="inv-kpi" style="border-left-color:var(--info);">
        <div class="inv-kpi-icon blue"><i class="fa fa-calendar-week"></i></div>
        <div class="inv-kpi-info">
            <div class="inv-kpi-val"><?php echo number_format($weekQty); ?></div>
            <div class="inv-kpi-label">Dispatched This Week</div>
        </div>
    </div>
    <div class="inv-kpi" style="border-left-color:var(--success);">
        <div class="inv-kpi-icon green"><i class="fa fa-shield-halved"></i></div>
        <div class="inv-kpi-info">
            <div class="inv-kpi-val"><?php echo number_format($secQty); ?></div>
            <div class="inv-kpi-label">Security Items</div>
        </div>
    </div>
    <div class="inv-kpi" style="border-left-color:var(--danger);">
        <div class="inv-kpi-icon red"><i class="fa fa-fire-extinguisher"></i></div>
        <div class="inv-kpi-info">
            <div class="inv-kpi-val"><?php echo number_format($fireQty); ?></div>
            <div class="inv-kpi-label">Fire Items</div>
        </div>
    </div>
    <div class="inv-kpi" style="border-left-color:var(--warning);">
        <div class="inv-kpi-icon orange"><i class="fa fa-chart-line"></i></div>
        <div class="inv-kpi-info">
            <div class="inv-kpi-val"><?php echo $avgPerReq; ?></div>
            <div class="inv-kpi-label">Avg Items / Request</div>
        </div>
    </div>
    <div class="inv-kpi" style="border-left-color:#7C3AED;">
        <div class="inv-kpi-icon purple"><i class="fa fa-layer-group"></i></div>
        <div class="inv-kpi-info">
            <div class="inv-kpi-val"><?php echo $activeCats; ?></div>
            <div class="inv-kpi-label">Active Categories</div>
        </div>
    </div>
</div>

<!-- ── ROW 1: Monthly Trend + Department Breakdown + Category Breakdown ── -->
<div class="inv-chart-grid-3">
    <!-- Monthly Trend (NEW) -->
    <div class="inv-panel">
        <div class="inv-panel-head">
            <h3><i class="fa fa-chart-line" style="color:var(--primary);margin-right:6px;"></i> 6-Month Dispatch Trend</h3>
            <span class="inv-panel-badge">Trend</span>
        </div>
        <div class="inv-panel-body">
            <div class="inv-chart-box-sm"><canvas id="chartTrend"></canvas></div>
        </div>
    </div>
    <!-- Department Breakdown (NEW) -->
    <div class="inv-panel">
        <div class="inv-panel-head">
            <h3><i class="fa fa-building" style="color:var(--info);margin-right:6px;"></i> By Department</h3>
            <span class="inv-panel-badge"><?php echo $monthShort; ?></span>
        </div>
        <div class="inv-panel-body">
            <div class="inv-chart-box-sm"><canvas id="chartDept"></canvas></div>
        </div>
    </div>
    <!-- Category Breakdown (NEW) -->
    <div class="inv-panel">
        <div class="inv-panel-head">
            <h3><i class="fa fa-tags" style="color:#7C3AED;margin-right:6px;"></i> By Category</h3>
            <span class="inv-panel-badge"><?php echo $monthShort; ?></span>
        </div>
        <div class="inv-panel-body">
            <div class="inv-chart-box-sm"><canvas id="chartCat"></canvas></div>
        </div>
    </div>
</div>

<!-- ── ROW 2: Installs Chart + Fire Chart ── -->
<div class="inv-chart-grid">
    <!-- Top 10 Installs -->
    <div class="inv-panel">
        <div class="inv-panel-head">
            <h3><i class="fa fa-shield-halved" style="color:var(--success);margin-right:6px;"></i> Top 10 Moving - Security Installs</h3>
            <span class="inv-panel-badge">Dept 9/10</span>
        </div>
        <div class="inv-panel-body">
            <div class="inv-chart-box"><canvas id="chartInstalls"></canvas></div>
        </div>
    </div>
    <!-- Top 10 Fire -->
    <div class="inv-panel">
        <div class="inv-panel-head">
            <h3><i class="fa fa-fire-extinguisher" style="color:var(--danger);margin-right:6px;"></i> Top 10 Moving - Fire</h3>
            <span class="inv-panel-badge">Dept 6/7/8</span>
        </div>
        <div class="inv-panel-body">
            <div class="inv-chart-box"><canvas id="chartFire"></canvas></div>
        </div>
    </div>
</div>

<!-- ── ROW 3: All-Time Top + Top Depts + Low Stock ── -->
<div class="inv-chart-grid-3">
    <!-- All Time Top SEC/FIRE -->
    <div class="inv-panel">
        <div class="inv-panel-head">
            <h3><i class="fa fa-trophy" style="color:var(--warning);margin-right:6px;"></i> All-Time Top Items</h3>
            <span class="inv-panel-badge">SEC + FIRE</span>
        </div>
        <div class="inv-panel-body">
            <div class="inv-chart-box"><canvas id="chartAllTime"></canvas></div>
        </div>
    </div>
    <!-- Top Requesting Departments (NEW) -->
    <div class="inv-panel">
        <div class="inv-panel-head">
            <h3><i class="fa fa-building-user" style="color:var(--primary);margin-right:6px;"></i> Top Requesting Depts</h3>
            <span class="inv-panel-badge"><?php echo $monthShort; ?></span>
        </div>
        <div class="inv-panel-body" style="max-height:310px;overflow-y:auto;">
            <ul class="inv-rank-list">
            <?php foreach($topDepts as $i=>$d): ?>
                <li>
                    <span class="inv-rank-num"><?php echo $i+1; ?></span>
                    <span class="inv-rank-name"><?php echo htmlspecialchars($d['departmentname']); ?></span>
                    <span class="inv-rank-val"><?php echo number_format($d['total_qty']); ?></span>
                    <span class="inv-rank-sub">(<?php echo $d['req_count']; ?> req)</span>
                </li>
            <?php endforeach; ?>
            <?php if(empty($topDepts)): ?><li style="color:var(--text-secondary);font-size:12px;">No data this month</li><?php endif; ?>
            </ul>
        </div>
    </div>
    <!-- Low Stock Alerts (NEW) -->
    <div class="inv-panel">
        <div class="inv-panel-head">
            <h3><i class="fa fa-triangle-exclamation" style="color:var(--danger);margin-right:6px;"></i> Low Stock Alerts</h3>
            <span class="inv-panel-badge" style="background:#FFF1F0;color:var(--danger);"><?php echo count($lowStockAlerts); ?> Items</span>
        </div>
        <div class="inv-panel-body" style="max-height:310px;overflow-y:auto;">
            <?php if(empty($lowStockAlerts)): ?>
                <div style="text-align:center;padding:30px;color:var(--success);"><i class="fa fa-circle-check" style="font-size:32px;"></i><div style="margin-top:8px;font-size:13px;font-weight:500;">All stock levels healthy</div></div>
            <?php else: ?>
                <?php foreach($lowStockAlerts as $al): 
                    $dotClass = ($al['total_onhand']<=0) ? 'red' : (($al['total_onhand']<=5) ? 'orange' : 'green');
                ?>
                <div class="inv-alert-row">
                    <span class="inv-alert-dot <?php echo $dotClass; ?>"></span>
                    <span class="inv-alert-name" title="<?php echo htmlspecialchars($al['description']); ?>"><?php echo htmlspecialchars($al['description']); ?></span>
                    <span class="inv-alert-cat"><?php echo $al['categoryid']; ?></span>
                    <span class="inv-alert-qty" style="color:<?php echo ($al['total_onhand']<=0)?'var(--danger)':'var(--warning)'; ?>;"><?php echo (int)$al['total_onhand']; ?></span>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- ── ROW 4: Stock On Hand by Location ── -->
<?php if(!empty($stockOnHand)): ?>
<div class="inv-panel" style="margin-bottom:24px;">
    <div class="inv-panel-head">
        <h3><i class="fa fa-warehouse" style="color:var(--primary);margin-right:6px;"></i> Stock On Hand by Location — Top SEC/FIRE Items</h3>
        <span class="inv-panel-badge">SUVA | NADI | NORTH</span>
    </div>
    <div class="inv-panel-body" style="overflow-x:auto;">
        <table class="inv-soh-table">
            <thead>
                <tr>
                    <th>Item</th>
                    <th style="text-align:center;">Dispatched (Month)</th>
                    <th style="text-align:center;">SUVA</th>
                    <th style="text-align:center;">NADI</th>
                    <th style="text-align:center;">NORTH</th>
                    <th style="text-align:center;">Total On Hand</th>
                    <th style="text-align:center;">Status</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach($stockOnHand as $soh):
                $total = $soh['suva']+$soh['nadi']+$soh['north'];
                $statusClass = ($total<=0)?'crit':(($total<=10)?'warn':'ok');
                $statusText = ($total<=0)?'Critical':(($total<=10)?'Low':'OK');
            ?>
                <tr>
                    <td style="font-weight:500;max-width:250px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="<?php echo htmlspecialchars($soh['desc']); ?>"><?php echo htmlspecialchars($soh['desc']); ?></td>
                    <td style="text-align:center;font-weight:600;"><?php echo number_format($soh['dispatched']); ?></td>
                    <td style="text-align:center;"><?php echo number_format($soh['suva']); ?></td>
                    <td style="text-align:center;"><?php echo number_format($soh['nadi']); ?></td>
                    <td style="text-align:center;"><?php echo number_format($soh['north']); ?></td>
                    <td style="text-align:center;font-weight:700;"><?php echo number_format($total); ?></td>
                    <td style="text-align:center;"><span class="inv-soh-badge <?php echo $statusClass; ?>"><?php echo $statusText; ?></span></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

</div><!-- end inv-dash-content -->

<!-- ═══════════════════ DATA TABLES ═══════════════════ -->
<div class="inv-section-title"><i class="fa fa-table"></i> Detailed Stock Movement Reports</div>

<!-- Table 1: Monthly Top 100 -->
<div class="inv-table-panel">
    <h3><i class="fa fa-calendar-days"></i> Top 100 Moving Items — <?php echo $monthName; ?></h3>
    <div class="table-responsive">
        <table id="projectreport" class="table">
            <thead>
                <tr>
                    <th>Stock ID</th>
                    <th>Description</th>
                    <th>Qty Dispatched</th>
                    <th>Department</th>
                    <th>Category</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach($monthlyRows as $mr): ?>
                <tr>
                    <td><?php echo htmlspecialchars($mr['stockid']); ?></td>
                    <td><?php echo htmlspecialchars($mr['description']); ?></td>
                    <td style="font-weight:600;"><?php echo number_format($mr['qtydelivered']); ?></td>
                    <td><?php echo htmlspecialchars($mr['departmentname']); ?></td>
                    <td><span style="background:var(--primary-light);color:var(--primary-dark);padding:2px 8px;border-radius:4px;font-size:11px;font-weight:600;"><?php echo htmlspecialchars($mr['categoryid']); ?></span></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Table 2: Weekly Top 30 -->
<div class="inv-table-panel">
    <h3><i class="fa fa-calendar-week"></i> Top 30 Moving Items — Last 7 Days</h3>
    <div class="table-responsive">
        <table id="projectreport2" class="table">
            <thead>
                <tr>
                    <th>Stock ID</th>
                    <th>Description</th>
                    <th>Qty Dispatched</th>
                    <th>Department</th>
                    <th>Category</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach($weeklyRows as $wr): ?>
                <tr>
                    <td><?php echo htmlspecialchars($wr['stockid']); ?></td>
                    <td><?php echo htmlspecialchars($wr['description']); ?></td>
                    <td style="font-weight:600;"><?php echo number_format($wr['qtydelivered']); ?></td>
                    <td><?php echo htmlspecialchars($wr['departmentname']); ?></td>
                    <td><span style="background:var(--primary-light);color:var(--primary-dark);padding:2px 8px;border-radius:4px;font-size:11px;font-weight:600;"><?php echo htmlspecialchars($wr['categoryid']); ?></span></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

</div><!-- end inv-dashboard -->

<!-- ═══════════════════ CHART.JS INITIALIZATION ═══════════════════ -->
<script>
document.addEventListener('DOMContentLoaded', function(){
    // Remove loading modal
    var lm = document.getElementById('dash-loading-modal');
    if(lm){lm.style.transition='opacity 0.4s';lm.style.opacity='0';setTimeout(function(){lm.remove();},400);}
    clearInterval(window._dashTimer);

    var tealPalette = ['#2AABB3','#1890FF','#52C41A','#FAAD14','#FF4D4F','#7C3AED','#F97316','#06B6D4','#EC4899','#8B5CF6','#10B981','#EF4444','#3B82F6','#F59E0B','#6366F1'];
    var tealBg = tealPalette.map(function(c){return c+'33';});

    var chartDefaults = {
        responsive:true, maintainAspectRatio:false,
        plugins:{legend:{display:false},tooltip:{backgroundColor:'#1F2937',titleFont:{family:'Poppins',size:12},bodyFont:{family:'Poppins',size:11},padding:10,cornerRadius:8}},
        scales:{x:{ticks:{font:{family:'Poppins',size:10}},grid:{display:false}},y:{ticks:{font:{family:'Poppins',size:10}},grid:{color:'#F3F4F6'}}}
    };

    // ── 6-Month Trend (Line) ──
    new Chart(document.getElementById('chartTrend'),{
        type:'line',
        data:{labels:<?php echo json_encode($trendLabels);?>,datasets:[{
            label:'Items Dispatched',data:<?php echo json_encode($trendData);?>,
            borderColor:'#2AABB3',backgroundColor:'rgba(42,171,179,0.1)',fill:true,tension:0.4,pointRadius:5,pointBackgroundColor:'#2AABB3',pointBorderColor:'#fff',pointBorderWidth:2,borderWidth:3
        }]},
        options:Object.assign({},chartDefaults)
    });

    // ── Department Doughnut ──
    new Chart(document.getElementById('chartDept'),{
        type:'doughnut',
        data:{labels:<?php echo json_encode($deptLabels);?>,datasets:[{data:<?php echo json_encode($deptData);?>,backgroundColor:tealPalette.slice(0,<?php echo count($deptLabels);?>),borderWidth:2,borderColor:'#fff'}]},
        options:{responsive:true,maintainAspectRatio:false,cutout:'60%',plugins:{legend:{position:'right',labels:{font:{family:'Poppins',size:10},padding:8,usePointStyle:true,pointStyle:'circle'}},tooltip:{backgroundColor:'#1F2937',titleFont:{family:'Poppins'},bodyFont:{family:'Poppins'},padding:10,cornerRadius:8}}}
    });

    // ── Category Doughnut ──
    new Chart(document.getElementById('chartCat'),{
        type:'doughnut',
        data:{labels:<?php echo json_encode($catLabels);?>,datasets:[{data:<?php echo json_encode($catData);?>,backgroundColor:tealPalette.slice(0,<?php echo count($catLabels);?>),borderWidth:2,borderColor:'#fff'}]},
        options:{responsive:true,maintainAspectRatio:false,cutout:'60%',plugins:{legend:{position:'right',labels:{font:{family:'Poppins',size:10},padding:8,usePointStyle:true,pointStyle:'circle'}},tooltip:{backgroundColor:'#1F2937',titleFont:{family:'Poppins'},bodyFont:{family:'Poppins'},padding:10,cornerRadius:8}}}
    });

    // ── Top 10 Installs (Horizontal Bar) ──
    new Chart(document.getElementById('chartInstalls'),{
        type:'bar',
        data:{labels:<?php echo json_encode($installLabels);?>,datasets:[{
            label:'Qty Dispatched',data:<?php echo json_encode($installData);?>,
            backgroundColor:tealBg.slice(0,<?php echo count($installLabels);?>),borderColor:tealPalette.slice(0,<?php echo count($installLabels);?>),borderWidth:1.5,borderRadius:4,barThickness:18
        }]},
        options:Object.assign({},chartDefaults,{indexAxis:'y',scales:{x:{ticks:{font:{family:'Poppins',size:10}},grid:{color:'#F3F4F6'}},y:{ticks:{font:{family:'Poppins',size:10},callback:function(v){var l=this.getLabelForValue(v);return l.length>25?l.substr(0,25)+'…':l;}},grid:{display:false}}}})
    });

    // ── Top 10 Fire (Horizontal Bar) ──
    new Chart(document.getElementById('chartFire'),{
        type:'bar',
        data:{labels:<?php echo json_encode($fireLabels);?>,datasets:[{
            label:'Qty Dispatched',data:<?php echo json_encode($fireData);?>,
            backgroundColor:<?php echo json_encode(array_map(function($c){return $c.'33';},array_slice(array('#FF4D4F','#F97316','#FAAD14','#2AABB3','#1890FF','#52C41A','#7C3AED','#EC4899','#06B6D4','#8B5CF6'),0,count($fireLabels))));?>,
            borderColor:<?php echo json_encode(array_slice(array('#FF4D4F','#F97316','#FAAD14','#2AABB3','#1890FF','#52C41A','#7C3AED','#EC4899','#06B6D4','#8B5CF6'),0,count($fireLabels)));?>,
            borderWidth:1.5,borderRadius:4,barThickness:18
        }]},
        options:Object.assign({},chartDefaults,{indexAxis:'y',scales:{x:{ticks:{font:{family:'Poppins',size:10}},grid:{color:'#F3F4F6'}},y:{ticks:{font:{family:'Poppins',size:10},callback:function(v){var l=this.getLabelForValue(v);return l.length>25?l.substr(0,25)+'…':l;}},grid:{display:false}}}})
    });

    // ── All-Time Top (Horizontal Bar) ──
    new Chart(document.getElementById('chartAllTime'),{
        type:'bar',
        data:{labels:<?php echo json_encode($allTimeLabels);?>,datasets:[{
            label:'Total Qty',data:<?php echo json_encode($allTimeData);?>,
            backgroundColor:tealBg.slice(0,<?php echo count($allTimeLabels);?>),borderColor:tealPalette.slice(0,<?php echo count($allTimeLabels);?>),borderWidth:1.5,borderRadius:4,barThickness:14
        }]},
        options:Object.assign({},chartDefaults,{indexAxis:'y',scales:{x:{ticks:{font:{family:'Poppins',size:10}},grid:{color:'#F3F4F6'}},y:{ticks:{font:{family:'Poppins',size:9},callback:function(v){var l=this.getLabelForValue(v);return l.length>22?l.substr(0,22)+'…':l;}},grid:{display:false}}}})
    });

    // ── DataTables ──
    $('#projectreport').DataTable({dom:'Bfrtip',order:[[2,'desc']],pageLength:25,buttons:[
        {extend:'pdfHtml5',orientation:'portrait',pageSize:'A4',customize:function(doc){doc.defaultStyle.fontSize=10;doc.defaultStyle.font='Helvetica';}},
        {extend:'excelHtml5'},{extend:'copyHtml5'}
    ]});
    $('#projectreport2').DataTable({dom:'Bfrtip',order:[[2,'desc']],pageLength:25,buttons:[
        {extend:'pdfHtml5',orientation:'portrait',pageSize:'A4',customize:function(doc){doc.defaultStyle.fontSize=10;doc.defaultStyle.font='Helvetica';}},
        {extend:'excelHtml5'},{extend:'copyHtml5'}
    ]});
});

// ── Dashboard Toggle with localStorage ──
function toggleInvDash(){
    var c=document.getElementById('invDashContent');
    var b=document.getElementById('invDashToggle');
    if(c.classList.contains('collapsed')){
        c.classList.remove('collapsed');
        b.classList.remove('collapsed');
        b.querySelector('span').textContent='Hide Dashboard';
        localStorage.setItem('invDashCollapsed','0');
    }else{
        c.classList.add('collapsed');
        b.classList.add('collapsed');
        b.querySelector('span').textContent='Show Dashboard';
        localStorage.setItem('invDashCollapsed','1');
    }
}
(function(){
    if(localStorage.getItem('invDashCollapsed')==='1'){
        var c=document.getElementById('invDashContent');
        var b=document.getElementById('invDashToggle');
        if(c&&b){c.classList.add('collapsed');b.classList.add('collapsed');b.querySelector('span').textContent='Show Dashboard';}
    }
})();
</script>

<?php
// ═══════════════════ ORIGINAL FOOTER/MENU LOGIC PRESERVED ═══════════════════
include('includes/MainMenuLinksArray.php');

if (isset($SupplierLogin) AND $SupplierLogin==1){
    echo '<table class="table_index">
            <tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=1">' . _('View or Amend outstanding offers') . '</a></p></td></tr>
            <tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=2">' . _('Create a new offer') . '</a></p></td></tr>
            <tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=3">' . _('View any open tenders without an offer') . '</a></p></td></tr>
          </table>';
    include('includes/footer.inc');
    exit;
} elseif (isset($CustomerLogin) AND $CustomerLogin==1){
    echo '<table class="table_index">
            <tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/CustomerInquiry.php?CustomerID=' . $_SESSION['CustomerID'] . '">' . _('Account Status') . '</a></p></td></tr>
            <tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SelectOrderItems.php?NewOrder=Yes">' . _('Place An Order') . '</a></p></td></tr>
            <tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SelectCompletedOrder.php?SelectedCustomer=' . $_SESSION['CustomerID'] . '">' . _('Order Status') . '</a></p></td></tr>
          </table>';
    include('includes/footer.inc');
    exit;
}

if (isset($_GET['Application'])){
    $_SESSION['Module'] = $_GET['Application'];
}
?>