<?php
/* Invoicing.php - Enhanced Invoicing Dashboard with CY/PY/Month scoping + Department Permissions */
error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity=0;
include('includes/session.inc');
$Title=_('Invoicing System');
include('includes/newheader.php');

$userid = $_SESSION['UserID'];
$userfullname = $_SESSION['UsersRealName'];
$timenow = date('Y-m-d H:i:s');
?>

<!-- ===== LOADING MODAL ===== -->
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<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>

<div id="invoicing-loading-modal" style="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(255,255,255,0.92);z-index:99999;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:inv-spin 0.8s linear infinite;margin:0 auto 16px;"></div>
    <div style="font-family:'Poppins',sans-serif;font-size:15px;color:#1F2937;font-weight:500;">Loading Invoicing Dashboard...</div>
    <div id="inv-load-timer" style="font-family:'Poppins',sans-serif;font-size:12px;color:#6B7280;margin-top:4px;">0s</div>
  </div>
</div>
<style>@keyframes inv-spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}</style>
<script>(function(){var s=0;var t=setInterval(function(){s++;var el=document.getElementById('inv-load-timer');if(el)el.textContent=s+'s';},1000);window._invLoadTimer=t;})();</script>
<?php if(function_exists('ob_flush')){ob_flush();}flush(); ?>

<?php
// ═══════════════════════════════════════════════════════════════
// DEPARTMENT PERMISSION FILTER - Applied to ALL dashboard queries
// ═══════════════════════════════════════════════════════════════
global $db;

$deptFilter = "";
$deptLabel = "All Departments";

if ($userid =='schand' || $userid =='stephanie') {
    $deptFilter = " AND department=6"; $deptLabel = "Fire Services";
} elseif ($userid =='waqa') {
    $deptFilter = " AND department=2"; $deptLabel = "Department 2";
} elseif ($userid =='nisha') {
    $deptFilter = " AND department=7"; $deptLabel = "Department 7";
} elseif ($userid =='lusi' || $userid =='mike') {
    $deptFilter = " AND department IN (9,10)"; $deptLabel = "Installs";
} elseif ($userid =='rajnesh') {
    $deptFilter = " AND department=3"; $deptLabel = "Department 3";
} elseif ($userid =='rowen' || $userid =='rramlu') {
    $deptFilter = " AND department IN (8,21)"; $deptLabel = "Departments 8/21";
} elseif ($userid =='vani' || $userid =='ruth' || $userid =='joseph' || $userid =='mosheed' || $userid =='roneelp' || $userid =='saula' || $userid =='vineshkumar') {
    $deptFilter = " AND department IN (2,3,7,9,10,13,14,16,19,23,28,29)"; $deptLabel = "Multi-Department";
} elseif ($userid =='ilimo' || $userid =='marica' || $userid =='semi') {
    $deptFilter = " AND department=1"; $deptLabel = "Department 1";
} elseif ($userid =='mere' || $userid =='sureta' || $userid =='lina' || $userid =='crispus') {
    $deptFilter = " AND department IN (9,11)"; $deptLabel = "Departments 9/11";
} elseif ($userid =='riaz') {
    $deptFilter = " AND department=11"; $deptLabel = "Department 11";
}

$isRestricted = ($deptFilter !== "");

// ═══════════════════════════════════════════════════════════════
// DATE SCOPING - Current Year, Previous Year, Current Month only
// ═══════════════════════════════════════════════════════════════
$CY = date('Y');       // 2026
$PY = $CY - 1;        // 2025
$curMonth = date('m');
$curMonthName = date('F');
$baseWhere = "WHERE cancelled=0 AND type=10" . $deptFilter;

// ── CY KPIs ──
$sql = "SELECT COUNT(*) as cnt, COALESCE(SUM(ovamount),0) as vep, COALESCE(SUM(ovgst),0) as vat, COALESCE(SUM(ovamount+ovgst),0) as vip, COALESCE(SUM(alloc),0) as alloc FROM debtortrans $baseWhere AND YEAR(trandate)=$CY";
$r = mysqli_query($db,$sql);
$cy = ($r) ? mysqli_fetch_assoc($r) : array();
$cyCnt   = isset($cy['cnt']) ? (int)$cy['cnt'] : 0;
$cyVEP   = isset($cy['vep']) ? (float)$cy['vep'] : 0;
$cyVAT   = isset($cy['vat']) ? (float)$cy['vat'] : 0;
$cyVIP   = isset($cy['vip']) ? (float)$cy['vip'] : 0;
$cyAlloc = isset($cy['alloc']) ? (float)$cy['alloc'] : 0;
$cyOuts  = $cyVIP - $cyAlloc;

// ── PY KPIs ──
$sql = "SELECT COUNT(*) as cnt, COALESCE(SUM(ovamount),0) as vep, COALESCE(SUM(ovgst),0) as vat, COALESCE(SUM(ovamount+ovgst),0) as vip, COALESCE(SUM(alloc),0) as alloc FROM debtortrans $baseWhere AND YEAR(trandate)=$PY";
$r = mysqli_query($db,$sql);
$py = ($r) ? mysqli_fetch_assoc($r) : array();
$pyCnt   = isset($py['cnt']) ? (int)$py['cnt'] : 0;
$pyVEP   = isset($py['vep']) ? (float)$py['vep'] : 0;
$pyVAT   = isset($py['vat']) ? (float)$py['vat'] : 0;
$pyVIP   = isset($py['vip']) ? (float)$py['vip'] : 0;
$pyAlloc = isset($py['alloc']) ? (float)$py['alloc'] : 0;
$pyOuts  = $pyVIP - $pyAlloc;

// ── Current Month KPIs ──
$sql = "SELECT COUNT(*) as cnt, COALESCE(SUM(ovamount+ovgst),0) as vip, COALESCE(SUM(ovamount),0) as vep FROM debtortrans $baseWhere AND MONTH(trandate)=$curMonth AND YEAR(trandate)=$CY";
$r = mysqli_query($db,$sql);
$cm = ($r) ? mysqli_fetch_assoc($r) : array();
$cmCnt = isset($cm['cnt']) ? (int)$cm['cnt'] : 0;
$cmVIP = isset($cm['vip']) ? (float)$cm['vip'] : 0;
$cmVEP = isset($cm['vep']) ? (float)$cm['vep'] : 0;

// ── Same Month Last Year (comparison) ──
$sql = "SELECT COUNT(*) as cnt, COALESCE(SUM(ovamount+ovgst),0) as vip FROM debtortrans $baseWhere AND MONTH(trandate)=$curMonth AND YEAR(trandate)=$PY";
$r = mysqli_query($db,$sql);
$smly = ($r) ? mysqli_fetch_assoc($r) : array();
$smlyCnt = isset($smly['cnt']) ? (int)$smly['cnt'] : 0;
$smlyVIP = isset($smly['vip']) ? (float)$smly['vip'] : 0;

// % changes
$vipYoY = ($pyVIP > 0) ? round((($cyVIP - $pyVIP) / $pyVIP) * 100, 1) : 0;
$cntYoY = ($pyCnt > 0) ? round((($cyCnt - $pyCnt) / $pyCnt) * 100, 1) : 0;
$monthYoY = ($smlyVIP > 0) ? round((($cmVIP - $smlyVIP) / $smlyVIP) * 100, 1) : 0;

// ── Chart: Monthly Trend CY vs PY (bar + line) ──
$trendCYLabels=array(); $trendCYAmts=array(); $trendCYCnts=array();
$trendPYAmts=array();
for($m=1;$m<=12;$m++){
    $mLabel = date('M', mktime(0,0,0,$m,1));
    $trendCYLabels[] = $mLabel;
    // CY
    $sql = "SELECT COALESCE(SUM(ovamount+ovgst),0) as amt, COUNT(*) as cnt FROM debtortrans $baseWhere AND MONTH(trandate)=$m AND YEAR(trandate)=$CY";
    $r = mysqli_query($db,$sql);
    $row = ($r) ? mysqli_fetch_assoc($r) : array('amt'=>0,'cnt'=>0);
    $trendCYAmts[] = round((float)(isset($row['amt'])?$row['amt']:0),2);
    $trendCYCnts[] = (int)(isset($row['cnt'])?$row['cnt']:0);
    // PY
    $sql = "SELECT COALESCE(SUM(ovamount+ovgst),0) as amt FROM debtortrans $baseWhere AND MONTH(trandate)=$m AND YEAR(trandate)=$PY";
    $r = mysqli_query($db,$sql);
    $row = ($r) ? mysqli_fetch_assoc($r) : array('amt'=>0);
    $trendPYAmts[] = round((float)(isset($row['amt'])?$row['amt']:0),2);
}

// ── Chart: Department Breakdown (CY only) ──
$sql = "SELECT d.departmentname as dept, COALESCE(SUM(t.ovamount+t.ovgst),0) as amt
    FROM debtortrans t LEFT JOIN department d ON t.department=d.departmentid
    $baseWhere AND YEAR(t.trandate)=$CY GROUP BY t.department ORDER BY amt DESC LIMIT 8";
$r = mysqli_query($db,$sql);
$deptLabels=array(); $deptAmts=array();
if($r){ while($row=mysqli_fetch_assoc($r)){
    $deptLabels[] = isset($row['dept']) ? $row['dept'] : 'Unknown';
    $deptAmts[] = round((float)$row['amt'],2);
}}

// ── Chart: Quarterly Comparison CY vs PY ──
$quarterLabels = array('Q1','Q2','Q3','Q4');
$qCY=array(); $qPY=array();
for($q=0;$q<4;$q++){
    $ms = ($q*3)+1; $me = ($q*3)+3;
    $sql = "SELECT COALESCE(SUM(ovamount+ovgst),0) as amt FROM debtortrans $baseWhere AND MONTH(trandate) BETWEEN $ms AND $me AND YEAR(trandate)=$CY";
    $r = mysqli_query($db,$sql); $row=($r)?mysqli_fetch_assoc($r):array('amt'=>0);
    $qCY[] = round((float)(isset($row['amt'])?$row['amt']:0),2);
    $sql = "SELECT COALESCE(SUM(ovamount+ovgst),0) as amt FROM debtortrans $baseWhere AND MONTH(trandate) BETWEEN $ms AND $me AND YEAR(trandate)=$PY";
    $r = mysqli_query($db,$sql); $row=($r)?mysqli_fetch_assoc($r):array('amt'=>0);
    $qPY[] = round((float)(isset($row['amt'])?$row['amt']:0),2);
}

// ── Recent 5 Invoices (CY) ──
$sql = "SELECT t.transno, t.trandate, t.ovamount, t.ovgst, (t.ovamount+t.ovgst) as vip, dm.name as customer 
    FROM debtortrans t LEFT JOIN debtorsmaster dm ON t.debtorno=dm.debtorno
    $baseWhere AND YEAR(t.trandate)>=$PY ORDER BY t.trandate DESC, t.transno DESC LIMIT 5";
$r = mysqli_query($db,$sql);
$recentInvoices = array();
if($r){ while($row=mysqli_fetch_assoc($r)){ $recentInvoices[]=$row; }}

// ── Top 5 Customers (CY) ──
$sql = "SELECT dm.name as customer, COUNT(*) as cnt, COALESCE(SUM(t.ovamount+t.ovgst),0) as amt
    FROM debtortrans t LEFT JOIN debtorsmaster dm ON t.debtorno=dm.debtorno
    $baseWhere AND YEAR(t.trandate)=$CY GROUP BY t.debtorno ORDER BY amt DESC LIMIT 5";
$r = mysqli_query($db,$sql);
$topCustomers = array();
if($r){ while($row=mysqli_fetch_assoc($r)){ $topCustomers[]=$row; }}

// ── Top 5 Customers (PY for comparison) ──
$sql = "SELECT dm.name as customer, COALESCE(SUM(t.ovamount+t.ovgst),0) as amt
    FROM debtortrans t LEFT JOIN debtorsmaster dm ON t.debtorno=dm.debtorno
    $baseWhere AND YEAR(t.trandate)=$PY GROUP BY t.debtorno ORDER BY amt DESC LIMIT 5";
$r = mysqli_query($db,$sql);
$topCustomersPY = array();
if($r){ while($row=mysqli_fetch_assoc($r)){ $topCustomersPY[]=$row; }}

// ── Monthly Invoice Count Heatmap Data (CY) ──
$heatData = array();
for($m=1;$m<=12;$m++){
    $sql = "SELECT COUNT(*) as cnt FROM debtortrans $baseWhere AND MONTH(trandate)=$m AND YEAR(trandate)=$CY";
    $r = mysqli_query($db,$sql); $row=($r)?mysqli_fetch_assoc($r):array('cnt'=>0);
    $heatData[] = (int)(isset($row['cnt'])?$row['cnt']:0);
}
?>

<style>
/* ===== GLOBAL VARS ===== */
:root {
    --inv-primary: #2AABB3;--inv-primary-dark: #1E8F96;--inv-primary-darker: #187278;
    --inv-light: #E6F7F8;--inv-success: #52C41A;--inv-warning: #FAAD14;
    --inv-danger: #FF4D4F;--inv-orange: #FA8C16;--inv-purple: #722ED1;
    --inv-border: #E5E7EB;--inv-text: #1F2937;--inv-text-secondary: #6B7280;
    --inv-bg: #F8FAFB;--inv-white: #FFFFFF;
    --inv-shadow: 0 1px 3px rgba(0,0,0,0.08);--inv-shadow-md: 0 4px 12px rgba(0,0,0,0.1);
    --inv-radius: 10px;--inv-font: 'Poppins', sans-serif;
}

/* ===== GRADIENT BANNER ===== */
.inv-banner{background:linear-gradient(135deg,var(--inv-primary-darker) 0%,var(--inv-primary) 50%,#34C8D1 100%);padding:28px 32px 24px;color:#fff;position:relative;overflow:hidden;margin:-15px -15px 0 -15px;}
.inv-banner::before{content:'';position:absolute;top:-50%;right:-10%;width:400px;height:400px;background:radial-gradient(circle,rgba(255,255,255,0.08) 0%,transparent 70%);border-radius:50%;}
.inv-banner::after{content:'';position:absolute;bottom:-30%;left:20%;width:250px;height:250px;background:radial-gradient(circle,rgba(255,255,255,0.05) 0%,transparent 70%);border-radius:50%;}
.inv-banner-content{position:relative;z-index:2;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:16px;}
.inv-banner h1{font-family:var(--inv-font);font-size:24px;font-weight:700;margin:0 0 4px;color:#fff;letter-spacing:-0.3px;}
.inv-banner p{font-family:var(--inv-font);font-size:13px;margin:0;opacity:0.85;font-weight:400;}
.inv-banner-actions{display:flex;gap:10px;flex-wrap:wrap;}
.inv-btn{font-family:var(--inv-font);padding:9px 20px;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;transition:all 0.2s;text-decoration:none!important;display:inline-flex;align-items:center;gap:7px;border:none;}
.inv-btn-white{background:#fff;color:var(--inv-primary-dark);}
.inv-btn-white:hover{background:#f0feff;transform:translateY(-1px);box-shadow:0 4px 12px rgba(0,0,0,0.15);color:var(--inv-primary-dark);text-decoration:none;}
.inv-btn-outline{background:rgba(255,255,255,0.15);color:#fff;border:1.5px solid rgba(255,255,255,0.4);}
.inv-btn-outline:hover{background:rgba(255,255,255,0.25);color:#fff;text-decoration:none;}

/* ===== BREADCRUMB ===== */
.inv-breadcrumb{font-family:var(--inv-font);padding:12px 32px;background:var(--inv-white);border-bottom:1px solid var(--inv-border);font-size:12.5px;color:var(--inv-text-secondary);margin:0 -15px;}
.inv-breadcrumb a{color:var(--inv-primary);text-decoration:none;}.inv-breadcrumb a:hover{text-decoration:underline;}
.inv-breadcrumb .sep{margin:0 8px;color:#D1D5DB;}

/* ===== SCOPE BADGE ===== */
.inv-scope-badge{display:inline-flex;align-items:center;gap:5px;padding:4px 12px;border-radius:20px;font-size:11px;font-weight:600;margin-left:8px;}
.inv-scope-badge.year{background:var(--inv-light);color:var(--inv-primary-dark);}
.inv-scope-badge.dept{background:#FFF7E6;color:var(--inv-orange);}

/* ===== TOGGLE ===== */
.inv-dash-toggle{font-family:var(--inv-font);display:flex;align-items:center;gap:8px;padding:10px 32px;background:var(--inv-white);border-bottom:1px solid var(--inv-border);cursor:pointer;user-select:none;margin:0 -15px;font-size:13px;font-weight:600;color:var(--inv-text);transition:background 0.15s;}
.inv-dash-toggle:hover{background:#FAFBFC;}
.inv-dash-toggle i.toggle-icon{transition:transform 0.3s;color:var(--inv-primary);}
.inv-dash-toggle.collapsed i.toggle-icon{transform:rotate(-90deg);}

/* ===== DASHBOARD ===== */
.inv-dashboard{background:var(--inv-bg);padding:24px 28px;margin:0 -15px;border-bottom:1px solid var(--inv-border);transition:max-height 0.4s ease,opacity 0.3s ease,padding 0.3s ease;max-height:4000px;opacity:1;overflow:hidden;}
.inv-dashboard.collapsed{max-height:0;opacity:0;padding:0 28px;border-bottom:none;}

/* ===== KPI CARDS ===== */
.inv-kpi-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:20px;}
.inv-kpi-card{background:var(--inv-white);border-radius:var(--inv-radius);padding:18px 20px;border-left:4px solid var(--inv-primary);box-shadow:var(--inv-shadow);display:flex;align-items:center;gap:14px;transition:transform 0.2s,box-shadow 0.2s;}
.inv-kpi-card:hover{transform:translateY(-2px);box-shadow:var(--inv-shadow-md);}
.inv-kpi-card.success{border-left-color:var(--inv-success);}.inv-kpi-card.warning{border-left-color:var(--inv-warning);}
.inv-kpi-card.danger{border-left-color:var(--inv-danger);}.inv-kpi-card.purple{border-left-color:var(--inv-purple);}
.inv-kpi-card.orange{border-left-color:var(--inv-orange);}
.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.primary{background:var(--inv-light);color:var(--inv-primary);}.inv-kpi-icon.success{background:#F0FFF4;color:var(--inv-success);}
.inv-kpi-icon.warning{background:#FFFBE6;color:var(--inv-warning);}.inv-kpi-icon.danger{background:#FFF1F0;color:var(--inv-danger);}
.inv-kpi-icon.purple{background:#F9F0FF;color:var(--inv-purple);}.inv-kpi-icon.orange{background:#FFF7E6;color:var(--inv-orange);}
.inv-kpi-icon.blue{background:#EBF5FF;color:#1890FF;}
.inv-kpi-info{flex:1;min-width:0;}
.inv-kpi-value{font-family:var(--inv-font);font-size:22px;font-weight:700;color:var(--inv-text);line-height:1.1;margin-bottom:2px;}
.inv-kpi-label{font-family:var(--inv-font);font-size:11px;color:var(--inv-text-secondary);font-weight:500;text-transform:uppercase;letter-spacing:0.4px;}
.inv-kpi-sub{font-family:var(--inv-font);font-size:11px;font-weight:600;margin-top:3px;}
.inv-kpi-sub.up{color:var(--inv-success);}.inv-kpi-sub.down{color:var(--inv-danger);}.inv-kpi-sub.neutral{color:var(--inv-text-secondary);}

/* ===== CHARTS ===== */
.inv-charts-row{display:grid;grid-template-columns:2fr 1fr;gap:16px;margin-bottom:20px;}
.inv-charts-row-equal{display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:20px;}
.inv-chart-card{background:var(--inv-white);border-radius:var(--inv-radius);box-shadow:var(--inv-shadow);overflow:hidden;}
.inv-chart-head{padding:14px 18px 10px;border-bottom:1px solid var(--inv-border);display:flex;align-items:center;justify-content:space-between;}
.inv-chart-head h3{margin:0;font-family:var(--inv-font);font-size:14px;font-weight:600;color:var(--inv-text);display:flex;align-items:center;gap:8px;}
.inv-chart-head h3 i{color:var(--inv-primary);font-size:14px;}
.inv-chart-badge{font-size:10px;padding:3px 10px;border-radius:20px;font-weight:600;background:var(--inv-light);color:var(--inv-primary-dark);}
.inv-chart-body{padding:16px 18px;}
.inv-chart-box{position:relative;height:260px;}
.inv-chart-box-lg{position:relative;height:300px;}

/* ===== PANELS ===== */
.inv-panels-row{display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:20px;}
.inv-panel-card{background:var(--inv-white);border-radius:var(--inv-radius);box-shadow:var(--inv-shadow);overflow:hidden;}
.inv-panel-header{font-family:var(--inv-font);padding:14px 18px;font-size:13px;font-weight:600;color:var(--inv-text);border-bottom:1px solid var(--inv-border);display:flex;align-items:center;gap:8px;}
.inv-panel-header i{color:var(--inv-primary);}
.inv-panel-item{font-family:var(--inv-font);display:flex;justify-content:space-between;align-items:center;padding:10px 18px;border-bottom:1px solid #F3F4F6;font-size:12.5px;transition:background 0.15s;}
.inv-panel-item:hover{background:#FAFBFC;}.inv-panel-item:last-child{border-bottom:none;}
.inv-panel-item .name{color:var(--inv-text);font-weight:500;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin-right:10px;}
.inv-panel-item .meta{color:var(--inv-text-secondary);font-size:11px;margin-right:12px;white-space:nowrap;}
.inv-panel-item .amount{font-weight:600;color:var(--inv-primary-dark);white-space:nowrap;}
.inv-panel-empty{font-family:var(--inv-font);padding:20px;text-align:center;color:var(--inv-text-secondary);font-size:12px;}
.inv-rank-num{width:22px;height:22px;border-radius:50%;background:var(--inv-light);color:var(--inv-primary-dark);font-size:10px;font-weight:700;display:flex;align-items:center;justify-content:center;flex-shrink:0;margin-right:8px;}

/* ===== XCRUD CSS OVERLAY (100% preserved from original) ===== */
.xcrud-container{margin:20px 0 0 0!important;font-family:var(--inv-font)!important;}
.xcrud .xcrud-top{background:var(--inv-white)!important;border:1px solid var(--inv-border)!important;border-bottom:none!important;border-radius:var(--inv-radius) var(--inv-radius) 0 0!important;padding:14px 18px!important;display:flex!important;align-items:center!important;flex-wrap:wrap!important;gap:8px!important;}
.xcrud .xcrud-top .xcrud-nav h3,.xcrud .xcrud-top h3{font-family:var(--inv-font)!important;font-size:16px!important;font-weight:600!important;color:var(--inv-text)!important;margin:0!important;}
.xcrud table.xcrud-list{font-family:var(--inv-font)!important;border-collapse:separate!important;border-spacing:0!important;border:1px solid var(--inv-border)!important;border-top:none!important;width:100%!important;font-size:12.5px!important;}
.xcrud table.xcrud-list thead tr th,.xcrud table.xcrud-list thead th{background:linear-gradient(180deg,#F8FAFB 0%,#F1F3F5 100%)!important;color:var(--inv-text)!important;font-weight:600!important;font-size:11.5px!important;text-transform:uppercase!important;letter-spacing:0.3px!important;padding:11px 12px!important;border-bottom:2px solid var(--inv-border)!important;white-space:nowrap!important;font-family:var(--inv-font)!important;}
.xcrud table.xcrud-list tbody tr td{padding:10px 12px!important;border-bottom:1px solid #F3F4F6!important;color:var(--inv-text)!important;font-family:var(--inv-font)!important;vertical-align:middle!important;font-size:12.5px!important;}
.xcrud table.xcrud-list tbody tr:hover td{background:#F0FDFE!important;}
.xcrud table.xcrud-list tbody tr:nth-child(even) td{background-color:#FAFBFC!important;}
.xcrud table.xcrud-list tbody tr:nth-child(even):hover td{background-color:#F0FDFE!important;}
.xcrud table.xcrud-list tbody tr[style*="background"] td{border-left:none!important;}
.xcrud input[type="text"],.xcrud input[type="search"],.xcrud select,.xcrud .xcrud-search input{font-family:var(--inv-font)!important;border:1.5px solid var(--inv-border)!important;border-radius:7px!important;padding:7px 12px!important;font-size:12.5px!important;transition:border-color 0.2s,box-shadow 0.2s!important;outline:none!important;color:var(--inv-text)!important;background:var(--inv-white)!important;}
.xcrud input[type="text"]:focus,.xcrud input[type="search"]:focus,.xcrud select:focus,.xcrud .xcrud-search input:focus{border-color:var(--inv-primary)!important;box-shadow:0 0 0 3px rgba(42,171,179,0.12)!important;}
.xcrud .xcrud-top a,.xcrud .xcrud-top button,.xcrud a.btn,.xcrud button.btn,.xcrud .xcrud-nav a{font-family:var(--inv-font)!important;border-radius:7px!important;font-size:12px!important;font-weight:500!important;padding:7px 14px!important;transition:all 0.2s!important;border:1.5px solid var(--inv-border)!important;background:var(--inv-white)!important;color:var(--inv-text)!important;text-decoration:none!important;}
.xcrud .xcrud-top a:hover,.xcrud .xcrud-top button:hover,.xcrud a.btn:hover,.xcrud button.btn:hover,.xcrud .xcrud-nav a:hover{border-color:var(--inv-primary)!important;color:var(--inv-primary)!important;background:var(--inv-light)!important;}
.xcrud td a.btn,.xcrud td button.btn,.xcrud .xcrud-action{font-family:var(--inv-font)!important;border-radius:6px!important;font-size:11px!important;padding:5px 10px!important;margin:1px 2px!important;font-weight:500!important;}
.xcrud td a.westpac,.xcrud td button.westpac{background:var(--inv-primary)!important;color:#fff!important;border-color:var(--inv-primary)!important;}
.xcrud td a.westpac:hover,.xcrud td button.westpac:hover{background:var(--inv-primary-dark)!important;border-color:var(--inv-primary-dark)!important;color:#fff!important;}
.xcrud td a.payslip,.xcrud td button.payslip{background:var(--inv-white)!important;color:var(--inv-danger)!important;border-color:var(--inv-danger)!important;}
.xcrud td a.payslip:hover,.xcrud td button.payslip:hover{background:#FFF1F0!important;color:var(--inv-danger)!important;}
.xcrud td a.payslipemail,.xcrud td button.payslipemail{background:var(--inv-white)!important;color:var(--inv-primary)!important;border-color:var(--inv-primary)!important;}
.xcrud .xcrud-nav,.xcrud .xcrud-pagination{font-family:var(--inv-font)!important;}
.xcrud .pagination>li>a,.xcrud .pagination>li>span{font-family:var(--inv-font)!important;border-radius:6px!important;margin:0 2px!important;border:1.5px solid var(--inv-border)!important;color:var(--inv-text)!important;font-size:12px!important;padding:6px 12px!important;}
.xcrud .pagination>.active>a,.xcrud .pagination>.active>span{background:var(--inv-primary)!important;border-color:var(--inv-primary)!important;color:#fff!important;}
.xcrud .pagination>li>a:hover{background:var(--inv-light)!important;border-color:var(--inv-primary)!important;color:var(--inv-primary)!important;}
.xcrud .xcrud-bottom{background:var(--inv-white)!important;border:1px solid var(--inv-border)!important;border-top:none!important;border-radius:0 0 var(--inv-radius) var(--inv-radius)!important;padding:12px 18px!important;font-family:var(--inv-font)!important;}
.xcrud table.xcrud-list tfoot tr td,.xcrud table.xcrud-list tr.xcrud-sum td{background:linear-gradient(180deg,#F0FDFE 0%,#E6F7F8 100%)!important;font-weight:700!important;color:var(--inv-primary-darker)!important;font-family:var(--inv-font)!important;padding:11px 12px!important;font-size:13px!important;border-top:2px solid var(--inv-primary)!important;}
.xcrud .xcrud-detail,.xcrud .xcrud-body,.xcrud-modal .modal-content{font-family:var(--inv-font)!important;border-radius:var(--inv-radius)!important;}
.xcrud .xcrud-detail table td,.xcrud .xcrud-detail table th{font-family:var(--inv-font)!important;padding:8px 12px!important;}
.xcrud .xcrud-nested{margin:8px 0!important;border-radius:8px!important;overflow:hidden!important;}
.xcrud .xcrud-nested .xcrud-list{border-radius:0!important;}
.xcrud .glyphicon{margin-right:4px!important;font-size:11px!important;}
.xcrud .xcrud-ajax{background:rgba(255,255,255,0.85)!important;}

@media(max-width:1200px){.inv-kpi-grid{grid-template-columns:repeat(3,1fr);}}
@media(max-width:992px){.inv-kpi-grid{grid-template-columns:repeat(2,1fr);}.inv-charts-row,.inv-charts-row-equal{grid-template-columns:1fr;}.inv-panels-row{grid-template-columns:1fr;}}
@media(max-width:768px){.inv-kpi-grid{grid-template-columns:1fr;}.inv-banner{padding:20px;}.inv-banner h1{font-size:20px;}.inv-dashboard{padding:16px;}}
@media print{.inv-banner,.inv-breadcrumb,.inv-dash-toggle,.inv-dashboard{display:none!important;}}
</style>

<!-- ═══════════════════ GRADIENT BANNER ═══════════════════ -->
<div class="inv-banner">
    <div class="inv-banner-content">
        <div>
            <h1><i class="fas fa-file-invoice-dollar" style="margin-right:10px;opacity:0.9;"></i>Invoicing System</h1>
            <p>Manage invoices, credit notes & billing &bull; <?php echo htmlspecialchars($userfullname); ?>
            <?php if($isRestricted): ?> &bull; <i class="fas fa-filter"></i> <?php echo $deptLabel; ?><?php endif; ?>
            </p>
        </div>
        <div class="inv-banner-actions">
            <a href="CreateInvoice.php" class="inv-btn inv-btn-white"><i class="fas fa-plus-circle"></i> Create Invoice</a>
            <a href="index.php" class="inv-btn inv-btn-outline"><i class="fas fa-home"></i> ERP Home</a>
        </div>
    </div>
</div>

<!-- ═══════════════════ BREADCRUMB ═══════════════════ -->
<div class="inv-breadcrumb">
    <a href="index.php">Home</a><span class="sep">/</span><a href="#">Finance</a><span class="sep">/</span>
    <strong style="color:var(--inv-text);">Invoicing System</strong>
    <span class="inv-scope-badge year"><i class="fas fa-calendar"></i> <?php echo $PY; ?> &ndash; <?php echo $CY; ?></span>
    <?php if($isRestricted): ?><span class="inv-scope-badge dept"><i class="fas fa-building"></i> <?php echo $deptLabel; ?></span><?php endif; ?>
</div>

<!-- ═══════════════════ TOGGLE ═══════════════════ -->
<div class="inv-dash-toggle" id="invDashToggle" onclick="toggleInvDashboard()">
    <i class="fas fa-chevron-down toggle-icon" id="invToggleIcon"></i>
    <span>Dashboard Overview</span>
    <span style="font-weight:400;color:var(--inv-text-secondary);font-size:11px;margin-left:8px;">
        — <?php echo number_format($cyCnt); ?> invoices in <?php echo $CY; ?>
        <?php if($isRestricted): ?> (<?php echo $deptLabel; ?>)<?php endif; ?>
    </span>
</div>

<!-- ═══════════════════ COLLAPSIBLE DASHBOARD ═══════════════════ -->
<div class="inv-dashboard" id="invDashboard">

    <!-- ── KPI ROW 1: Current Year ── -->
    <div style="font-family:var(--inv-font);font-size:12px;font-weight:600;color:var(--inv-text-secondary);text-transform:uppercase;letter-spacing:0.8px;margin-bottom:10px;display:flex;align-items:center;gap:6px;">
        <i class="fas fa-chart-bar" style="color:var(--inv-primary);"></i> CURRENT YEAR <?php echo $CY; ?>
        <?php if($pyCnt > 0): ?>
        <span style="font-weight:400;text-transform:none;letter-spacing:0;margin-left:8px;color:<?php echo ($vipYoY>=0)?'var(--inv-success)':'var(--inv-danger)'; ?>;">
            <?php echo ($vipYoY>=0)?'▲':'▼'; ?> <?php echo abs($vipYoY); ?>% vs <?php echo $PY; ?>
        </span>
        <?php endif; ?>
    </div>
    <div class="inv-kpi-grid">
        <div class="inv-kpi-card">
            <div class="inv-kpi-icon primary"><i class="fas fa-file-invoice"></i></div>
            <div class="inv-kpi-info">
                <div class="inv-kpi-value"><?php echo number_format($cyCnt); ?></div>
                <div class="inv-kpi-label">Invoices (<?php echo $CY; ?>)</div>
                <div class="inv-kpi-sub <?php echo ($cntYoY>=0)?'up':'down'; ?>"><?php echo ($cntYoY>=0)?'▲':'▼'; ?> <?php echo abs($cntYoY); ?>% vs <?php echo $PY; ?> (<?php echo number_format($pyCnt); ?>)</div>
            </div>
        </div>
        <div class="inv-kpi-card success">
            <div class="inv-kpi-icon success"><i class="fas fa-dollar-sign"></i></div>
            <div class="inv-kpi-info">
                <div class="inv-kpi-value">$<?php echo number_format($cyVEP,2); ?></div>
                <div class="inv-kpi-label">VEP Amount (<?php echo $CY; ?>)</div>
                <div class="inv-kpi-sub neutral"><?php echo $PY; ?>: $<?php echo number_format($pyVEP,2); ?></div>
            </div>
        </div>
        <div class="inv-kpi-card warning">
            <div class="inv-kpi-icon warning"><i class="fas fa-percentage"></i></div>
            <div class="inv-kpi-info">
                <div class="inv-kpi-value">$<?php echo number_format($cyVAT,2); ?></div>
                <div class="inv-kpi-label">VAT (<?php echo $CY; ?>)</div>
                <div class="inv-kpi-sub neutral"><?php echo $PY; ?>: $<?php echo number_format($pyVAT,2); ?></div>
            </div>
        </div>
        <div class="inv-kpi-card purple">
            <div class="inv-kpi-icon purple"><i class="fas fa-calculator"></i></div>
            <div class="inv-kpi-info">
                <div class="inv-kpi-value">$<?php echo number_format($cyVIP,2); ?></div>
                <div class="inv-kpi-label">Total VIP (<?php echo $CY; ?>)</div>
                <div class="inv-kpi-sub neutral"><?php echo $PY; ?>: $<?php echo number_format($pyVIP,2); ?></div>
            </div>
        </div>
    </div>

    <!-- ── KPI ROW 2: Month + Outstanding ── -->
    <div class="inv-kpi-grid" style="grid-template-columns:repeat(4,1fr);margin-bottom:20px;">
        <div class="inv-kpi-card" style="border-left-color:#1890FF;">
            <div class="inv-kpi-icon blue"><i class="fas fa-calendar-day"></i></div>
            <div class="inv-kpi-info">
                <div class="inv-kpi-value"><?php echo number_format($cmCnt); ?></div>
                <div class="inv-kpi-label"><?php echo $curMonthName; ?> <?php echo $CY; ?> Invoices</div>
                <div class="inv-kpi-sub <?php echo ($monthYoY>=0)?'up':'down'; ?>">
                    <?php echo ($monthYoY>=0)?'▲':'▼'; ?> <?php echo abs($monthYoY); ?>% vs <?php echo $curMonthName.' '.$PY; ?> (<?php echo $smlyCnt; ?>)
                </div>
            </div>
        </div>
        <div class="inv-kpi-card orange">
            <div class="inv-kpi-icon orange"><i class="fas fa-coins"></i></div>
            <div class="inv-kpi-info">
                <div class="inv-kpi-value">$<?php echo number_format($cmVIP,2); ?></div>
                <div class="inv-kpi-label"><?php echo $curMonthName; ?> Revenue</div>
                <div class="inv-kpi-sub neutral">VEP: $<?php echo number_format($cmVEP,2); ?></div>
            </div>
        </div>
        <div class="inv-kpi-card" style="border-left-color:var(--inv-success);">
            <div class="inv-kpi-icon success"><i class="fas fa-hand-holding-dollar"></i></div>
            <div class="inv-kpi-info">
                <div class="inv-kpi-value">$<?php echo number_format($cyAlloc,2); ?></div>
                <div class="inv-kpi-label">Allocated (<?php echo $CY; ?>)</div>
            </div>
        </div>
        <div class="inv-kpi-card danger">
            <div class="inv-kpi-icon danger"><i class="fas fa-exclamation-triangle"></i></div>
            <div class="inv-kpi-info">
                <div class="inv-kpi-value">$<?php echo number_format($cyOuts,2); ?></div>
                <div class="inv-kpi-label">Outstanding (<?php echo $CY; ?>)</div>
                <div class="inv-kpi-sub neutral"><?php echo $PY; ?>: $<?php echo number_format($pyOuts,2); ?></div>
            </div>
        </div>
    </div>

    <!-- ── CHARTS ROW 1: Monthly Trend CY vs PY + Department Doughnut ── -->
    <div class="inv-charts-row">
        <div class="inv-chart-card">
            <div class="inv-chart-head">
                <h3><i class="fas fa-chart-line"></i> Monthly Revenue: <?php echo $CY; ?> vs <?php echo $PY; ?></h3>
                <span class="inv-chart-badge">Year Comparison</span>
            </div>
            <div class="inv-chart-body"><div class="inv-chart-box-lg"><canvas id="invTrendChart"></canvas></div></div>
        </div>
        <div class="inv-chart-card">
            <div class="inv-chart-head">
                <h3><i class="fas fa-chart-pie"></i> By Department</h3>
                <span class="inv-chart-badge"><?php echo $CY; ?></span>
            </div>
            <div class="inv-chart-body"><div class="inv-chart-box-lg"><canvas id="invDeptChart"></canvas></div></div>
        </div>
    </div>

    <!-- ── CHARTS ROW 2: Quarterly Comparison + Invoice Count Heatmap ── -->
    <div class="inv-charts-row-equal">
        <div class="inv-chart-card">
            <div class="inv-chart-head">
                <h3><i class="fas fa-layer-group"></i> Quarterly Comparison</h3>
                <span class="inv-chart-badge"><?php echo $CY; ?> vs <?php echo $PY; ?></span>
            </div>
            <div class="inv-chart-body"><div class="inv-chart-box"><canvas id="invQuarterChart"></canvas></div></div>
        </div>
        <div class="inv-chart-card">
            <div class="inv-chart-head">
                <h3><i class="fas fa-th"></i> Monthly Invoice Volume</h3>
                <span class="inv-chart-badge"><?php echo $CY; ?></span>
            </div>
            <div class="inv-chart-body"><div class="inv-chart-box"><canvas id="invVolumeChart"></canvas></div></div>
        </div>
    </div>

    <!-- ── PANELS: Recent + Top Customers ── -->
    <div class="inv-panels-row">
        <div class="inv-panel-card">
            <div class="inv-panel-header"><i class="fas fa-clock"></i> Recent Invoices</div>
            <?php if(count($recentInvoices)>0): ?>
                <?php foreach($recentInvoices as $ri): ?>
                <div class="inv-panel-item">
                    <span class="name" title="<?php echo htmlspecialchars(isset($ri['customer'])?$ri['customer']:''); ?>">
                        <strong>#<?php echo htmlspecialchars($ri['transno']); ?></strong> — <?php echo htmlspecialchars(isset($ri['customer'])?$ri['customer']:'N/A'); ?>
                    </span>
                    <span class="meta"><?php echo htmlspecialchars($ri['trandate']); ?></span>
                    <span class="amount">$<?php echo number_format((float)$ri['vip'],2); ?></span>
                </div>
                <?php endforeach; ?>
            <?php else: ?><div class="inv-panel-empty">No recent invoices</div><?php endif; ?>
        </div>
        <div class="inv-panel-card">
            <div class="inv-panel-header"><i class="fas fa-trophy"></i> Top Customers (<?php echo $CY; ?>)</div>
            <?php if(count($topCustomers)>0): ?>
                <?php $rank=1; foreach($topCustomers as $tc): ?>
                <div class="inv-panel-item">
                    <span class="inv-rank-num"><?php echo $rank++; ?></span>
                    <span class="name" title="<?php echo htmlspecialchars(isset($tc['customer'])?$tc['customer']:''); ?>">
                        <?php echo htmlspecialchars(isset($tc['customer'])?$tc['customer']:'Unknown'); ?>
                    </span>
                    <span class="meta"><?php echo (int)$tc['cnt']; ?> inv</span>
                    <span class="amount">$<?php echo number_format((float)$tc['amt'],2); ?></span>
                </div>
                <?php endforeach; ?>
            <?php else: ?><div class="inv-panel-empty">No customer data</div><?php endif; ?>
        </div>
    </div>

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

<!-- ═══════════════════ CHART.JS INITIALIZATION ═══════════════════ -->
<script>
document.addEventListener('DOMContentLoaded', function(){
    var P = ['#2AABB3','#722ED1','#FA8C16','#52C41A','#FF4D4F','#1890FF','#EB2F96','#FAAD14'];

    // ── Monthly Trend: CY bars + PY line ──
    new Chart(document.getElementById('invTrendChart'),{
        type:'bar',
        data:{
            labels:<?php echo json_encode($trendCYLabels);?>,
            datasets:[
                {label:'<?php echo $CY; ?> Revenue ($)',data:<?php echo json_encode($trendCYAmts);?>,backgroundColor:'rgba(42,171,179,0.7)',borderColor:'#2AABB3',borderWidth:1,borderRadius:5,barPercentage:0.5,order:2},
                {label:'<?php echo $PY; ?> Revenue ($)',data:<?php echo json_encode($trendPYAmts);?>,type:'line',borderColor:'#722ED1',backgroundColor:'rgba(114,46,209,0.08)',borderWidth:2.5,pointRadius:4,pointBackgroundColor:'#722ED1',tension:0.3,fill:true,order:1},
                {label:'<?php echo $CY; ?> Count',data:<?php echo json_encode($trendCYCnts);?>,type:'line',borderColor:'#FA8C16',backgroundColor:'transparent',borderWidth:2,borderDash:[5,3],pointRadius:3,pointBackgroundColor:'#FA8C16',tension:0.3,yAxisID:'y1',order:0}
            ]
        },
        options:{
            responsive:true,maintainAspectRatio:false,
            interaction:{mode:'index',intersect:false},
            plugins:{legend:{position:'top',labels:{font:{family:'Poppins',size:11},usePointStyle:true,padding:14}}},
            scales:{
                x:{grid:{display:false},ticks:{font:{family:'Poppins',size:10}}},
                y:{position:'left',grid:{color:'#F3F4F6'},ticks:{font:{family:'Poppins',size:10},callback:function(v){return '$'+(v>=1000?(v/1000).toFixed(0)+'k':v);}}},
                y1:{position:'right',grid:{display:false},ticks:{font:{family:'Poppins',size:10}}}
            }
        }
    });

    // ── Department Doughnut ──
    new Chart(document.getElementById('invDeptChart'),{
        type:'doughnut',
        data:{labels:<?php echo json_encode($deptLabels);?>,datasets:[{data:<?php echo json_encode($deptAmts);?>,backgroundColor:P,borderWidth:2,borderColor:'#fff'}]},
        options:{responsive:true,maintainAspectRatio:false,cutout:'60%',plugins:{legend:{position:'right',labels:{font:{family:'Poppins',size:10},padding:10,usePointStyle:true}},tooltip:{callbacks:{label:function(c){return c.label+': $'+c.parsed.toLocaleString();}}}}}
    });

    // ── Quarterly Comparison ──
    new Chart(document.getElementById('invQuarterChart'),{
        type:'bar',
        data:{labels:<?php echo json_encode($quarterLabels);?>,datasets:[
            {label:'<?php echo $CY; ?>',data:<?php echo json_encode($qCY);?>,backgroundColor:'rgba(42,171,179,0.75)',borderColor:'#2AABB3',borderWidth:1,borderRadius:6,barPercentage:0.4},
            {label:'<?php echo $PY; ?>',data:<?php echo json_encode($qPY);?>,backgroundColor:'rgba(114,46,209,0.5)',borderColor:'#722ED1',borderWidth:1,borderRadius:6,barPercentage:0.4}
        ]},
        options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{labels:{font:{family:'Poppins',size:11},usePointStyle:true,padding:14}}},scales:{x:{grid:{display:false},ticks:{font:{family:'Poppins',size:11,weight:'bold'}}},y:{grid:{color:'#F3F4F6'},ticks:{font:{family:'Poppins',size:10},callback:function(v){return '$'+(v>=1000?(v/1000).toFixed(0)+'k':v);}}}}}
    });

    // ── Monthly Volume (bar chart with gradient feel) ──
    var volData = <?php echo json_encode($heatData);?>;
    var maxVol = Math.max.apply(null,volData)||1;
    var volColors = volData.map(function(v){var r=v/maxVol; return r>0.7?'rgba(42,171,179,0.85)':r>0.4?'rgba(42,171,179,0.55)':'rgba(42,171,179,0.3)';});
    new Chart(document.getElementById('invVolumeChart'),{
        type:'bar',
        data:{labels:<?php echo json_encode($trendCYLabels);?>,datasets:[{label:'Invoice Count',data:volData,backgroundColor:volColors,borderColor:'#2AABB3',borderWidth:1,borderRadius:4,barPercentage:0.6}]},
        options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{display:false},tooltip:{callbacks:{title:function(c){return c[0].label+' <?php echo $CY; ?>';},label:function(c){return c.parsed.y+' invoices';}}}},scales:{x:{grid:{display:false},ticks:{font:{family:'Poppins',size:10}}},y:{grid:{color:'#F3F4F6'},ticks:{font:{family:'Poppins',size:10}}}}}
    });

    // Remove loading modal
    var modal=document.getElementById('invoicing-loading-modal');
    if(modal){modal.style.transition='opacity 0.4s';modal.style.opacity='0';setTimeout(function(){modal.remove();},400);}
    if(window._invLoadTimer)clearInterval(window._invLoadTimer);
});

// Dashboard toggle with localStorage
function toggleInvDashboard(){
    var d=document.getElementById('invDashboard'),t=document.getElementById('invDashToggle');
    if(d.classList.contains('collapsed')){d.classList.remove('collapsed');t.classList.remove('collapsed');localStorage.setItem('inv_dash_collapsed','0');}
    else{d.classList.add('collapsed');t.classList.add('collapsed');localStorage.setItem('inv_dash_collapsed','1');}
}
(function(){if(localStorage.getItem('inv_dash_collapsed')==='1'){var d=document.getElementById('invDashboard'),t=document.getElementById('invDashToggle');if(d)d.classList.add('collapsed');if(t)t.classList.add('collapsed');}})();
</script>

<!-- ═══════════════════ XCRUD TABLE (100% PRESERVED) ═══════════════════ -->
<div style="padding: 0; margin: 0 -15px;">
<?php
    include('xcrud/xcrud.php');
    $invoices= Xcrud::get_instance();
    $invoices->table('debtortrans');
    
    $invoices->where('cancelled=', 0); 
    $invoices->where('type=',10); 
    if ($userid =='schand' ||$userid =='stephanie' ){
        $invoices->where('department=',6);
    }
    if ($userid =='waqa'){
        $invoices->where('department=',2);
    }
    if ($userid =='nisha'){
        $invoices->where('department=',7);
    }
    if ($userid =='lusi' ){
        $invoices->where('department', array('9','10'));
    }
    if ($userid =='mike'){
        $invoices->where('department', array('9','10'));
    }
    if ($userid =='rajnesh'){
        $invoices->where('department=',3);
    }
    if ($userid =='rowen' || $userid =='rramlu'){
        $invoices->where('department', array('8','21'));
    }
    if ($userid =='vani' || $userid =='ruth' || $userid =='joseph'|| $userid =='mosheed'||$userid =='roneelp'||$userid =='saula'  ||$userid =='vineshkumar' ){
        $invoices->where('department', array('2','3','7','9','10','13','14','16','19','23','28','29'));
    }
    if ($userid =='ilimo' ||$userid =='marica'  ||$userid =='semi'){
        $invoices->where('department=',1);
    }
    if ($userid =='vani' ||$userid =='ravinesh' ||$userid =='nitika' ||$userid =='matai'||$userid =='hola' ||$userid =='sadiyah' ){
        // no additional filter
    }
    if ($userid =='mere' ||$userid =='sureta' ||$userid =='lina' ||$userid =='crispus' ){
        $invoices->where('department=',array('9','11'));
    }
    if ($userid =='riaz' ){
        $invoices->where('department=',11);
    }

    $invoices->unset_add();
    $invoices->unset_remove();
    $invoices->order_by('trandate,transno','desc');
    $invoices->fields('transno,order_,projectid,debtorno,contact_person,account_number,department,lpo,cash_customer_name,cash_customer_address,trandate,ovamount,ovgst,total_vip,alloc,ptax,retention,invtext,sales_gl,old_sales_code,old_gl_code,entered_date,cancelled,entered_by,modified_by,modified_datetime,cancelled_by,gl_status',false);
    $invoices->columns('transno,order_,projectid,debtorno,contact_person,account_number,department,lpo,cash_customer_name,cash_customer_address,trandate,ovamount,ovgst,total_vip,alloc,ptax,retention,invtext,sales_gl,old_sales_code,old_gl_code,entered_date,cancelled,entered_by,modified_by,modified_datetime,cancelled_by,gl_status',false);
    $invoices->label('transno','Invoice no:');
    $invoices->label('trandate','Dated:');
    $invoices->label('projectid','Job No/Project ID:');
    $invoices->label('order_','Order No');
    $invoices->label('ovamount','VEP Amount');
    $invoices->label('billing_id','CIT Bill ID');
    $invoices->table_name('Invoicing System');
    $invoices->button('JCPrintInvoice.php?bill_id={bill_id}&billing_id={billing_id}&orderno={order_}&transno={transno}&debtorno={debtorno}&ovamount={ovamount}&vat={ovgst}&total_vip={total_vip}&trandate={trandate}', 'Re-Print Invoice','glyphicon glyphicon-download-alt','westpac');
    $invoices->button('CancelInvoice.php?orderno={order_}&transno={transno}', 'Cancel this Invoice','glyphicon glyphicon-retweet','payslip');
    $invoices->button('CreditInvoice.php?orderno={order_}&transno={transno}&debtorno={debtorno}', 'Credit Note','glyphicon glyphicon-cog','payslip');
    $invoices->relation('debtorno','debtorsmaster','debtorno','name');
    $invoices->highlight_row('ovamount','<','1000','#e6ff99');
    $invoices->highlight_row('ovamount','>','1000','#ffe6ff');
    $invoices->highlight_row('ovamount','>','5000','#ffcce0');
    $invoices->relation('department','department','departmentid','departmentname'); 
    $invoices->subselect('total_vip','{ovamount}+{ovgst}');
    $invoices->label('ovgst','Vat');
    $invoices->pass_var('modified_by',$userfullname );
    $invoices->pass_var('modified_datetime',$timenow);
    $invoices->sum('ovamount,ovgst,total_vip');
    $invoices->change_type('ovamount,ovgst,total_vip', 'price', '0', array('prefix'=>'$','decimals'=>'2'));
    $invoices->relation('sales_gl','chartmaster','accountcode',array('accountcode','accountname'),array('group_' => 'Sales'));
    $invoices->relation('projectid','projectdetails','projectid',array('project_name','wip_income'));

    // Nested table: Line Item Details
    $salesorderdetails = $invoices->nested_table('Item Line Details','order_','salesorderdetails','orderno');
    $salesorderdetails->table_name('Line item Details');
    $salesorderdetails->fields('stkcode,stock_name,qtyinvoiced,unitprice,quantity,discountpercent,narrative,total',false);
    $salesorderdetails->columns('stkcode,stock_name,qtyinvoiced,unitprice,quantity,discountpercent,narrative,total',false);
    $salesorderdetails->subselect('total','{unitprice}*{quantity}');
    $salesorderdetails->sum('total');
    $salesorderdetails->change_type('total,unitprice', 'price', '0', array('prefix'=>'$','decimals'=>'2'));

    // Nested table: Account Details
    $account = $invoices->nested_table('Account Details','account_number','debtoraccount','account_number');
    $account->relation('debtorno','debtorsmaster','debtorno',array('name','debtorno'));
    $account->relation('branchcode','custbranch','branchcode','brname','','','','','','branchcode','debtorno');
    $account->relation('departmentid','department','departmentid','departmentname');
    $account->label('debtorno','Customer Name');
    $account->label('branchcode','Customer Branch');
    $account->label('divisionid','Division');
    $account->label('departmentid','Department');
    $account->pass_default('modified_by',$userid);
    $account->pass_var('modified_by',$userid );
    $account->pass_default('date_modified',$timenow);
    $account->pass_var('date_modified',$timenow );
    $account->column_name('debtorno','Customer Name');
    $account->column_name('branchcode','Customer Branch');
    $account->label('divisionid','Division');
    $account->label('departmentid','Department');
    $account->column_name('divisionid','Division');
    $account->column_name('departmentid','Department'); 
    $account->table_name('Customer Account Management');
    $account->sum('balance');
    $account->highlight('divisionid','=','Guardforce','#e6ff99');
    $account->highlight('divisionid','=','Enablement','#e6ffff');
    $account->highlight('divisionid','=','Monitoring','#ffe6ff');
    $account->highlight('divisionid','=','Security Installs','#ffcce0');
    $account->highlight('divisionid','=','Fire  Installs','#ff9980');
    $account->highlight('divisionid','=','Cash in Transit','#ffe680');
    $account->order_by('account_number','desc');
    $account->column_pattern('debtorno', '<a href="#" class="xcrud-action" data-task="view" data-primary="{account_number}">{value}</a>');

    // Nested table: Customer Details (inside Account Details)
    $details = $account->nested_table('Customer Details','debtorno','debtorsmaster','debtorno');
    $details->unset_add();
    $details->unset_remove();
    $details->unset_edit();
    $details->disabled('debtorno');
    $details->label('address1','Street Address');
    $details->label('address2','Street Address');
    $details->label('address3','Surburb');
    $details->label('address4','State');
    $details->label('address5','PostCode');
    $details->label('address6','Country');

    echo $invoices->render();

    echo '</div>';
    echo '</div>';
    echo '</div>';
?>
                    </div>
                </div>
            </div>

                <!--end:: Widgets/Stats-->
                <!--Begin::Section-->

    <!-- end::Quick Sidebar -->
    <div id="m_scroll_top" class="m-scroll-top"><i class="la la-arrow-up"></i></div>

<script src="includes/vendors/owl.carousel/dist/owl.carousel.js" type="text/javascript"></script>
    </body>
</html>
      
<?php
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'];
}

function GetRptLinks($GroupID) {
    global $db, $RootPath, $ReportList;
    require_once('reportwriter/languages/en_US/reports.php');
    require_once('reportwriter/admin/defaults.php');
    $GroupID=$ReportList[$GroupID];
    $Title= array(_('Custom Reports'), _('Standard Reports and Forms'));
    $sql= "SELECT id, reporttype, defaultreport, groupname, reportname FROM reports ORDER BY groupname, reportname";
    $Result=DB_query($sql,'','',false,true);
    $ReportList = '';
    while ($Temp = DB_fetch_array($Result)) $ReportList[] = $Temp;
    $RptLinks = '';
    for ($Def=1; $Def>=0; $Def--) {
        $RptLinks .= '<li class="menu_group_headers"><b>' . $Title[$Def] . '</b></li>';
        $NoEntries = true;
        if ($ReportList) {
            foreach ($ReportList as $Report) {
                if ($Report['groupname']==$GroupID AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/reportwriter/ReportMaker.php?action=go&amp;reportid=' . $Report['id'] . '">' . _($Report['reportname']) . '</a></p></li>';
                    $NoEntries = false;
                }
            }
            $NoForms = true;
            foreach ($ReportList as $Report) {
                $Group=explode(':',$Report['groupname']);
                if ($NoForms AND $Group[0]==$GroupID AND $Report['reporttype']=='frm' AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item"><img src="' . $RootPath . '/css/' . $_SESSION['Theme'] . '/images/folders.gif" width="16" height="13" alt="" />&nbsp;<p>&bull; <a href="' . $RootPath . '/reportwriter/FormMaker.php?id=' . $Report['groupname'] . '"></p>' . $FormGroups[$Report['groupname']] . '</a></li>';
                    $NoForms = false;
                    $NoEntries = false;
                }
            }
        }
        if ($NoEntries) $RptLinks .= '<li class="menu_group_item">' . _('There are no reports to show!') . '</li>';
    }
    return $RptLinks;
}
?>

<!-- Modal HTML -->
<div id="ex1" class="modal"><p>Thanks for clicking. That felt good.</p><a href="#" rel="modal:close">Close</a></div>

<div class="modal fade" id="getCodeModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
   <div class="modal-dialog modal-lg">
      <div class="modal-content">
       <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
         <h4 class="modal-title" id="myModalLabel"> API CODE </h4>
       </div>
       <div class="modal-body" id="getCode" style="overflow-x: scroll;"></div>
    </div>
   </div>
</div>

<script>
jQuery(document).ready(function($){
    $(".xcrud").on("change","#internal",function(){
        var internal = $("#internal").val();
        if(internal != 0){$('#sectors').attr("disabled",true);$('#patrollocation').attr("disabled",true);$('#account').attr("disabled",true);}
        else{$('#sectors').attr("disabled",false);$('#patrollocation').attr("disabled",false);$('#account').attr("disabled",false);}
    });
    
    var days=['mon','tues','wed','thurs','fri','sat','sun'];
    $.each(days,function(i,day){
        $(".xcrud").on("change","#"+day+"out",function(){
            var start_time=$("#"+day+"in").val();var end_time=$("#"+day+"out").val();
            var rosterid=$("#rosterid").val();var employeeid=$("#employeeid").val();
            if(day!='mon' && end_time<=start_time){alert('Time logged out has to be greater than Time logged in');}
            $.ajax({url:'hrms/CheckEmployee-timeclash'+day+'.php',method:"POST",
                data:{start_time:start_time,end_time:end_time,rosterid:rosterid,employeeid:employeeid},
                success:function(data){var data=JSON.parse(data);if(data!=0){alert('CLASH! This employee is already rostered in another location/post at these selected times. Please choose another employee. Details: ROSTERID:'+data);}}
            });
        });
    });
});
</script>
<script type="text/javascript">jQuery(document).on("ready xcrudafterrequest",function(){});</script>