<?php
/* PurchaseOrders.php - Enhanced with Ant Design Dashboard + Chart.js */
error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity=0;

/* ── API Mode ── */
if (isset($_GET['api']) && $_GET['api'] === 'dashboard') {
    ob_start();
    include('includes/session.inc');
    ob_end_clean();
    header('Content-Type: application/json');
    
    $db_host = 'localhost';
    $db_user = 'sooggoo';
    $db_pass = '4Compassion*';
    $db_name = isset($_SESSION['DatabaseName']) ? $_SESSION['DatabaseName'] : 'evergreenint';
    $dbc = new mysqli($db_host, $db_user, $db_pass, $db_name);
    if ($dbc->connect_error) { echo json_encode(array('error'=>'DB connection failed')); exit; }
    
    $userid = $_SESSION['UserID'];
    $curYear = date('Y');
    $curMonth = date('m');
    $prevYear = $curYear - 1;
    
    /* ── Department Filter ── */
    $deptMap = array(
        'admin'=>'ALL','sharukh'=>'ALL','ravinesh'=>'ALL','eseta'=>'ALL','jtukana'=>'ALL','shiv'=>'ALL','priyakumar'=>'ALL',
        'schand'=>array(6,8,29),'stephanie'=>array(6,8,29),'losa'=>array(6,8,29),'manueli'=>array(6,8,29),
        'nisha'=>array(7,29),'douglas'=>array(7,29),'akumar'=>array(7,29),
        'lusi'=>array(2,10,21,29),'mike'=>array(2,10,21,29),'riaz'=>array(2,10,21,29),
        'mosheed'=>array(1,2,6,7,9,10,13,14,16,19,23,28,29),'ronil'=>array(1,2,6,7,9,10,13,14,16,19,23,28,29),
        'sala'=>array(1,2,6,7,9,10,13,14,16,19,23,28,29),'roneelp'=>array(1,2,6,7,9,10,13,14,16,19,23,28,29),
        'saula'=>array(1,2,6,7,9,10,13,14,16,19,23,28,29),'vineshkumar'=>array(1,2,6,7,9,10,13,14,16,19,23,28,29),
        'menani'=>array(1,2,6,7,9,10,13,14,16,19,23,28,29),
        'maraia'=>array(18,19,28,29),'ashil'=>array(18,19,28,29),'vani'=>array(18,19,28,29),'serge'=>array(18,19,28,29),
        'rajnesh'=>array(3,29),
        'rowen'=>array(8,21,29),'rramlu'=>array(8,21,29),
        'asenacacagi'=>array(2,29),'liti'=>array(2,29),'maca'=>array(2,29),'ronald'=>array(2,29),
        'seni'=>array(2,29),'tarusila'=>array(2,29),'wili'=>array(2,29),'mairewa'=>array(2,29),'lani'=>array(2,29),
        'annie'=>array(1,3,29),'salata'=>array(1,3,29),'jokaveti'=>array(1,3,29),'auliasi'=>array(1,3,29),
        'alumita'=>array(1,3,29),'alisi'=>array(1,3,29),'asenaca'=>array(1,3,29),'lavenia'=>array(1,3,29),
        'marenda'=>array(1,3,29),'kalesim'=>array(1,3,29),'ilimo'=>array(1,3,29),'jpenjueli'=>array(1,3,29),
        'marica'=>array(1,3,29),
        'mere'=>array(9,11,29),'zubia'=>array(9,11,29),'eugene'=>array(9,11,29),'sureta'=>array(9,11,29),
        'crispus'=>array(9,11,29),'lina'=>array(9,11,29),
        'mkhan'=>array(22,23,29),'pchand'=>array(22,23,29),'walesi'=>array(22,23,29)
    );
    
    $deptFilter = '';
    if (isset($deptMap[$userid])) {
        $d = $deptMap[$userid];
        if ($d !== 'ALL') {
            $ids = implode(',', array_map('intval', $d));
            $deptFilter = " AND po.department IN ($ids)";
        }
    }
    
    $data = array();
    
    /* KPI 1: Total POs this year */
    $r = $dbc->query("SELECT COUNT(*) AS cnt FROM purchorders po WHERE YEAR(po.orddate)='$curYear' $deptFilter");
    $data['total_cy'] = ($r && $row=$r->fetch_assoc()) ? (int)$row['cnt'] : 0;
    
    /* KPI 2: Total POs last year */
    $r = $dbc->query("SELECT COUNT(*) AS cnt FROM purchorders po WHERE YEAR(po.orddate)='$prevYear' $deptFilter");
    $data['total_py'] = ($r && $row=$r->fetch_assoc()) ? (int)$row['cnt'] : 0;
    
    /* KPI 3: YTD Value this year */
    $r = $dbc->query("SELECT COALESCE(SUM(pod.unitprice*pod.quantityord),0) AS val 
                       FROM purchorders po 
                       INNER JOIN purchorderdetails pod ON po.orderno=pod.orderno 
                       WHERE YEAR(po.orddate)='$curYear' $deptFilter");
    $data['ytd_val_cy'] = ($r && $row=$r->fetch_assoc()) ? round((float)$row['val'],2) : 0;
    
    /* KPI 4: YTD Value last year */
    $r = $dbc->query("SELECT COALESCE(SUM(pod.unitprice*pod.quantityord),0) AS val 
                       FROM purchorders po 
                       INNER JOIN purchorderdetails pod ON po.orderno=pod.orderno 
                       WHERE YEAR(po.orddate)='$prevYear' $deptFilter");
    $data['ytd_val_py'] = ($r && $row=$r->fetch_assoc()) ? round((float)$row['val'],2) : 0;
    
    /* KPI 5: This month POs */
    $r = $dbc->query("SELECT COUNT(*) AS cnt FROM purchorders po WHERE YEAR(po.orddate)='$curYear' AND MONTH(po.orddate)='$curMonth' $deptFilter");
    $data['month_cnt'] = ($r && $row=$r->fetch_assoc()) ? (int)$row['cnt'] : 0;
    
    /* KPI 6: This month value */
    $r = $dbc->query("SELECT COALESCE(SUM(pod.unitprice*pod.quantityord),0) AS val 
                       FROM purchorders po 
                       INNER JOIN purchorderdetails pod ON po.orderno=pod.orderno 
                       WHERE YEAR(po.orddate)='$curYear' AND MONTH(po.orddate)='$curMonth' $deptFilter");
    $data['month_val'] = ($r && $row=$r->fetch_assoc()) ? round((float)$row['val'],2) : 0;
    
    /* KPI 7: Pending count */
    $r = $dbc->query("SELECT COUNT(*) AS cnt FROM purchorders po WHERE po.status='Pending' $deptFilter");
    $data['pending'] = ($r && $row=$r->fetch_assoc()) ? (int)$row['cnt'] : 0;
    
    /* KPI 8: Authorised count */
    $r = $dbc->query("SELECT COUNT(*) AS cnt FROM purchorders po WHERE (po.status='Authorised' OR po.status='Printed') $deptFilter");
    $data['authorised'] = ($r && $row=$r->fetch_assoc()) ? (int)$row['cnt'] : 0;
    
    /* KPI 9: Avg PO Value this year */
    $r = $dbc->query("SELECT COALESCE(AVG(tot),0) AS avgval FROM (
                       SELECT SUM(pod.unitprice*pod.quantityord) AS tot 
                       FROM purchorders po 
                       INNER JOIN purchorderdetails pod ON po.orderno=pod.orderno 
                       WHERE YEAR(po.orddate)='$curYear' $deptFilter
                       GROUP BY po.orderno) sub");
    $data['avg_po_val'] = ($r && $row=$r->fetch_assoc()) ? round((float)$row['avgval'],2) : 0;
    
    /* KPI 10: Unique suppliers this year */
    $r = $dbc->query("SELECT COUNT(DISTINCT po.supplierno) AS cnt FROM purchorders po WHERE YEAR(po.orddate)='$curYear' $deptFilter");
    $data['unique_suppliers'] = ($r && $row=$r->fetch_assoc()) ? (int)$row['cnt'] : 0;
    
    /* KPI 11: Outstanding (uncompleted) items value */
    $r = $dbc->query("SELECT COALESCE(SUM(pod.unitprice*(pod.quantityord-pod.quantityrecd)),0) AS val 
                       FROM purchorders po 
                       INNER JOIN purchorderdetails pod ON po.orderno=pod.orderno 
                       WHERE pod.completed=0 $deptFilter");
    $data['outstanding_val'] = ($r && $row=$r->fetch_assoc()) ? round((float)$row['val'],2) : 0;
    
    /* KPI 12: Fully received this year */
    $r = $dbc->query("SELECT COUNT(DISTINCT po.orderno) AS cnt 
                       FROM purchorders po 
                       INNER JOIN purchorderdetails pod ON po.orderno=pod.orderno 
                       WHERE YEAR(po.orddate)='$curYear' AND pod.completed=1 $deptFilter");
    $data['received_cy'] = ($r && $row=$r->fetch_assoc()) ? (int)$row['cnt'] : 0;
    
    /* CHART 1: Monthly PO trend (current year) */
    $monthlyTrend = array();
    $r = $dbc->query("SELECT MONTH(po.orddate) AS m, COUNT(*) AS cnt, COALESCE(SUM(pod.unitprice*pod.quantityord),0) AS val 
                       FROM purchorders po 
                       INNER JOIN purchorderdetails pod ON po.orderno=pod.orderno 
                       WHERE YEAR(po.orddate)='$curYear' $deptFilter
                       GROUP BY MONTH(po.orddate) ORDER BY m");
    if ($r) { while ($row=$r->fetch_assoc()) { $monthlyTrend[] = $row; } }
    $data['monthly_trend'] = $monthlyTrend;
    
    /* CHART 2: Monthly PO trend (previous year) */
    $monthlyTrendPY = array();
    $r = $dbc->query("SELECT MONTH(po.orddate) AS m, COUNT(*) AS cnt, COALESCE(SUM(pod.unitprice*pod.quantityord),0) AS val 
                       FROM purchorders po 
                       INNER JOIN purchorderdetails pod ON po.orderno=pod.orderno 
                       WHERE YEAR(po.orddate)='$prevYear' $deptFilter
                       GROUP BY MONTH(po.orddate) ORDER BY m");
    if ($r) { while ($row=$r->fetch_assoc()) { $monthlyTrendPY[] = $row; } }
    $data['monthly_trend_py'] = $monthlyTrendPY;
    
    /* CHART 3: Top 6 suppliers by value this year */
    $topSuppliers = array();
    $r = $dbc->query("SELECT s.suppname, COALESCE(SUM(pod.unitprice*pod.quantityord),0) AS val, COUNT(DISTINCT po.orderno) AS cnt
                       FROM purchorders po 
                       INNER JOIN purchorderdetails pod ON po.orderno=pod.orderno 
                       INNER JOIN suppliers s ON po.supplierno=s.supplierid
                       WHERE YEAR(po.orddate)='$curYear' $deptFilter
                       GROUP BY s.suppname ORDER BY val DESC LIMIT 6");
    if ($r) { while ($row=$r->fetch_assoc()) { $topSuppliers[] = $row; } }
    $data['top_suppliers'] = $topSuppliers;
    
    /* CHART 4: Department breakdown this year */
    $deptBreak = array();
    $r = $dbc->query("SELECT d.departmentname, COALESCE(SUM(pod.unitprice*pod.quantityord),0) AS val, COUNT(DISTINCT po.orderno) AS cnt
                       FROM purchorders po 
                       INNER JOIN purchorderdetails pod ON po.orderno=pod.orderno 
                       INNER JOIN department d ON po.department=d.departmentid
                       WHERE YEAR(po.orddate)='$curYear' $deptFilter
                       GROUP BY d.departmentname ORDER BY val DESC LIMIT 8");
    if ($r) { while ($row=$r->fetch_assoc()) { $deptBreak[] = $row; } }
    $data['dept_breakdown'] = $deptBreak;
    
    /* CHART 5: Status distribution */
    $statusDist = array();
    $r = $dbc->query("SELECT po.status, COUNT(*) AS cnt FROM purchorders po WHERE YEAR(po.orddate)='$curYear' $deptFilter GROUP BY po.status ORDER BY cnt DESC");
    if ($r) { while ($row=$r->fetch_assoc()) { $statusDist[] = $row; } }
    $data['status_dist'] = $statusDist;
    
    /* CHART 6: Top 8 most ordered stock items this year */
    $topItems = array();
    $r = $dbc->query("SELECT pod.itemdescription, SUM(pod.quantityord) AS qty, COALESCE(SUM(pod.unitprice*pod.quantityord),0) AS val
                       FROM purchorders po 
                       INNER JOIN purchorderdetails pod ON po.orderno=pod.orderno 
                       WHERE YEAR(po.orddate)='$curYear' AND pod.itemdescription != '' $deptFilter
                       GROUP BY pod.itemdescription ORDER BY val DESC LIMIT 8");
    if ($r) { while ($row=$r->fetch_assoc()) { $topItems[] = $row; } }
    $data['top_items'] = $topItems;
    
    /* TABLE: Recent 5 POs */
    $recentPOs = array();
    $r = $dbc->query("SELECT po.orderno, po.orddate, po.status, po.initiator, s.suppname, 
                       COALESCE(SUM(pod.unitprice*pod.quantityord),0) AS val, d.departmentname
                       FROM purchorders po 
                       INNER JOIN purchorderdetails pod ON po.orderno=pod.orderno 
                       INNER JOIN suppliers s ON po.supplierno=s.supplierid
                       INNER JOIN department d ON po.department=d.departmentid
                       WHERE YEAR(po.orddate)='$curYear' $deptFilter
                       GROUP BY po.orderno ORDER BY po.orderno DESC LIMIT 5");
    if ($r) { while ($row=$r->fetch_assoc()) { $recentPOs[] = $row; } }
    $data['recent_pos'] = $recentPOs;
    
    $data['cur_year'] = (int)$curYear;
    $data['prev_year'] = (int)$prevYear;
    
    $dbc->close();
    echo json_encode($data);
    exit;
}

/* ── Normal Page Render ── */
include('includes/session.inc');
$Title=_('Purchase Orders');
include('includes/newheader.php');
?>

<!-- Loading Modal -->
<div id="poLoadingModal" style="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(255,255,255,0.92);z-index:9999;display:flex;align-items:center;justify-content:center;flex-direction:column;font-family:'Poppins',sans-serif;">
    <div style="width:48px;height:48px;border:4px solid #E6F7F8;border-top-color:#2AABB3;border-radius:50%;animation:poSpin 0.8s linear infinite;margin-bottom:16px;"></div>
    <div style="font-size:15px;font-weight:600;color:#1F2937;">Loading Purchase Orders</div>
    <div style="font-size:12px;color:#6B7280;margin-top:4px;" id="poLoadTimer">Preparing dashboard...</div>
</div>
<style>@keyframes poSpin{to{transform:rotate(360deg)}}</style>
<?php ob_flush(); flush(); ?>

<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>

<style>
/* ── Base ── */
.po-app * { box-sizing: border-box; margin: 0; padding: 0; }
.po-app {
    font-family: 'Poppins', -apple-system, BlinkMacSystemFont, sans-serif;
    color: #1F2937; max-width: 1440px; margin: 0 auto; padding: 0 20px 40px;
}

/* ── Banner ── */
.po-banner {
    background: linear-gradient(135deg, #1E8F96 0%, #2AABB3 50%, #35C4CD 100%);
    border-radius: 16px; padding: 28px 32px; margin: 16px 0 20px; color: #fff;
    position: relative; overflow: hidden;
    box-shadow: 0 4px 24px rgba(42,171,179,0.25);
}
.po-banner::before { content:''; position:absolute; top:-40px; right:-40px; width:180px; height:180px; background:rgba(255,255,255,0.06); border-radius:50%; }
.po-banner::after { content:''; position:absolute; bottom:-50px; right:100px; width:140px; height:140px; background:rgba(255,255,255,0.04); border-radius:50%; }
.po-bc { display:flex; align-items:center; gap:8px; font-size:12px; color:rgba(255,255,255,0.8); margin-bottom:10px; }
.po-bc a { color:rgba(255,255,255,0.8); text-decoration:none; } .po-bc a:hover { color:#fff; }
.po-bc .sep { opacity:0.5; }
.po-banner h1 { font-size:22px; font-weight:700; margin-bottom:4px; letter-spacing:-0.3px; }
.po-banner p { font-size:13px; opacity:0.85; font-weight:300; }
.po-banner-row { display:flex; gap:28px; margin-top:14px; padding-top:12px; border-top:1px solid rgba(255,255,255,0.15); flex-wrap:wrap; }
.po-banner-stat .sv { font-size:20px; font-weight:700; } .po-banner-stat .sl { font-size:10px; opacity:0.8; text-transform:uppercase; letter-spacing:0.5px; }

/* ── Toggle ── */
.po-toggle { display:flex; align-items:center; gap:8px; cursor:pointer; font-size:13px; color:#6B7280; font-weight:500; margin-bottom:14px; user-select:none; padding:7px 14px; background:#F9FAFB; border-radius:8px; width:fit-content; transition:color 0.2s; }
.po-toggle:hover { color:#2AABB3; }
.po-toggle i.chv { transition:transform 0.3s; font-size:11px; }
.po-toggle.collapsed i.chv { transform:rotate(-90deg); }
.po-dash { overflow:hidden; transition:max-height 0.4s ease, opacity 0.3s; max-height:1200px; opacity:1; }
.po-dash.collapsed { max-height:0; opacity:0; }

/* ── KPI Cards ── */
.po-kpi-row { display:grid; grid-template-columns:repeat(4,1fr); gap:14px; margin-bottom:16px; }
.po-kpi {
    background:#fff; border-radius:12px; padding:16px 18px; border-left:4px solid #2AABB3;
    box-shadow:0 1px 6px rgba(0,0,0,0.05); transition:transform 0.2s, box-shadow 0.2s; position:relative;
}
.po-kpi:hover { transform:translateY(-2px); box-shadow:0 4px 16px rgba(0,0,0,0.1); }
.po-kpi-top { display:flex; align-items:center; justify-content:space-between; margin-bottom:8px; }
.po-kpi-icon { width:36px; height:36px; border-radius:9px; display:flex; align-items:center; justify-content:center; font-size:15px; }
.po-kpi .kv { font-size:22px; font-weight:700; color:#1F2937; line-height:1.1; }
.po-kpi .kl { font-size:11px; color:#6B7280; font-weight:500; text-transform:uppercase; letter-spacing:0.4px; margin-top:3px; }
.po-kpi .kd { font-size:10px; margin-top:4px; font-weight:600; display:inline-flex; align-items:center; gap:3px; padding:2px 7px; border-radius:10px; }
.kd-up { background:#E8F8E8; color:#389E0D; } .kd-down { background:#FFF1F0; color:#CF1322; } .kd-flat { background:#F3F4F6; color:#6B7280; }
.ic-teal { background:#E6F7F8; color:#2AABB3; }
.ic-green { background:#E8F8E8; color:#52C41A; }
.ic-orange { background:#FFF4E6; color:#FAAD14; }
.ic-blue { background:#E8F4FD; color:#1890FF; }
.ic-purple { background:#F3E8FF; color:#722ED1; }
.ic-red { background:#FFF1F0; color:#FF4D4F; }

/* ── Chart Cards ── */
.po-charts { display:grid; grid-template-columns:repeat(2,1fr); gap:14px; margin-bottom:16px; }
.po-chart-card { background:#fff; border-radius:12px; box-shadow:0 1px 6px rgba(0,0,0,0.05); border:1px solid #E5E7EB; overflow:hidden; }
.po-chart-head { padding:12px 16px; border-bottom:1px solid #F0F0F0; display:flex; align-items:center; gap:8px; font-size:13px; font-weight:600; color:#1F2937; }
.po-chart-head i { color:#2AABB3; font-size:14px; }
.po-chart-body { padding:14px 16px; position:relative; }
.po-chart-body canvas { max-height:200px !important; }

/* ── Recent Table ── */
.po-recent { background:#fff; border-radius:12px; box-shadow:0 1px 6px rgba(0,0,0,0.05); border:1px solid #E5E7EB; overflow:hidden; margin-bottom:16px; }
.po-recent-head { padding:12px 16px; border-bottom:1px solid #F0F0F0; display:flex; align-items:center; justify-content:space-between; background:#FAFBFC; }
.po-recent-head-left { display:flex; align-items:center; gap:8px; font-size:13px; font-weight:600; color:#1F2937; }
.po-recent-head-left i { color:#2AABB3; }
.po-recent table { width:100%; border-collapse:collapse; }
.po-recent th { background:#F9FAFB; font-size:11px; font-weight:600; text-transform:uppercase; letter-spacing:0.4px; color:#6B7280; padding:10px 14px; text-align:left; border-bottom:1px solid #E5E7EB; }
.po-recent td { font-size:12px; padding:10px 14px; border-bottom:1px solid #F0F0F0; color:#374151; }
.po-recent tr:hover { background:#F0FAFB; }
.po-sbadge { display:inline-block; padding:2px 8px; border-radius:8px; font-size:10px; font-weight:600; }
.po-sb-pending { background:#FFF4E6; color:#AD6800; }
.po-sb-authorised,.po-sb-printed { background:#E8F8E8; color:#389E0D; }
.po-sb-cancelled,.po-sb-rejected { background:#FFF1F0; color:#CF1322; }
.po-sb-departmentalauthorised { background:#E8F4FD; color:#096DD9; }

/* ── xcrud overlay ── */
.po-app .xcrud-container { border-radius:12px!important; overflow:hidden!important; box-shadow:0 1px 6px rgba(0,0,0,0.05)!important; border:1px solid #E5E7EB!important; }
.po-app .xcrud-nav { background:linear-gradient(135deg,#1E8F96,#2AABB3)!important; }
.po-app .xcrud-nav a,.po-app .xcrud-nav span { color:#fff!important; font-family:'Poppins',sans-serif!important; }
.po-app .xcrud-top-actions { background:#FAFBFC!important; border-bottom:1px solid #E5E7EB!important; padding:10px 16px!important; }
.po-app .xcrud-list-container { font-family:'Poppins',sans-serif!important; }
.po-app .xcrud-row { border-bottom:1px solid #F0F0F0!important; }
.po-app .xcrud-row:hover { background:#F0FAFB!important; }
.po-app .xcrud-row td { font-size:12px!important; padding:8px 10px!important; }
.po-app .xcrud-thead th { background:linear-gradient(135deg,#1E8F96,#2AABB3)!important; color:#fff!important; font-family:'Poppins',sans-serif!important; font-size:11px!important; font-weight:600!important; text-transform:uppercase!important; letter-spacing:0.4px!important; padding:10px!important; }

/* ── Responsive ── */
@media(max-width:1024px) { .po-kpi-row { grid-template-columns:repeat(2,1fr); } .po-charts { grid-template-columns:1fr; } }
@media(max-width:640px) { .po-kpi-row { grid-template-columns:1fr; } .po-banner { padding:20px; } .po-banner h1 { font-size:18px; } .po-banner-row { gap:14px; } }
</style>

<div class="po-app">

<!-- Banner -->
<div class="po-banner">
    <div class="po-bc">
        <a href="index.php"><i class="fas fa-home"></i></a><span class="sep">/</span>
        <a href="index.php">Purchasing</a><span class="sep">/</span>
        <span>Purchase Orders</span>
    </div>
    <h1><i class="fas fa-file-invoice-dollar" style="margin-right:10px;opacity:0.9;"></i>Purchase Orders</h1>
    <p>Comprehensive purchase order management with real-time analytics</p>
    <div class="po-banner-row" id="bannerStats">
        <div class="po-banner-stat"><div class="sv" id="bTotal">--</div><div class="sl">This Year POs</div></div>
        <div class="po-banner-stat"><div class="sv" id="bValue">--</div><div class="sl">YTD Value</div></div>
        <div class="po-banner-stat"><div class="sv" id="bPending">--</div><div class="sl">Pending</div></div>
        <div class="po-banner-stat"><div class="sv" id="bSuppliers">--</div><div class="sl">Active Suppliers</div></div>
    </div>
</div>

<!-- Toggle -->
<div class="po-toggle" id="poToggle" onclick="togglePoDash()">
    <i class="fas fa-chevron-down chv"></i><span>Dashboard Analytics</span>
</div>

<!-- Dashboard -->
<div class="po-dash" id="poDash">
    <!-- KPI Row 1 -->
    <div class="po-kpi-row" id="kpiRow1"></div>
    <!-- KPI Row 2 -->
    <div class="po-kpi-row" id="kpiRow2"></div>
    
    <!-- Charts Row 1 -->
    <div class="po-charts">
        <div class="po-chart-card">
            <div class="po-chart-head"><i class="fas fa-chart-line"></i>Monthly PO Value Trend</div>
            <div class="po-chart-body"><canvas id="chartTrend"></canvas></div>
        </div>
        <div class="po-chart-card">
            <div class="po-chart-head"><i class="fas fa-chart-bar"></i>Monthly PO Count</div>
            <div class="po-chart-body"><canvas id="chartCount"></canvas></div>
        </div>
    </div>
    
    <!-- Charts Row 2 -->
    <div class="po-charts">
        <div class="po-chart-card">
            <div class="po-chart-head"><i class="fas fa-truck"></i>Top Suppliers by Value</div>
            <div class="po-chart-body"><canvas id="chartSuppliers"></canvas></div>
        </div>
        <div class="po-chart-card">
            <div class="po-chart-head"><i class="fas fa-sitemap"></i>Department Spend</div>
            <div class="po-chart-body"><canvas id="chartDept"></canvas></div>
        </div>
    </div>
    
    <!-- Charts Row 3 -->
    <div class="po-charts">
        <div class="po-chart-card">
            <div class="po-chart-head"><i class="fas fa-tags"></i>Status Distribution</div>
            <div class="po-chart-body"><canvas id="chartStatus"></canvas></div>
        </div>
        <div class="po-chart-card">
            <div class="po-chart-head"><i class="fas fa-cubes"></i>Top Items by Value</div>
            <div class="po-chart-body"><canvas id="chartItems"></canvas></div>
        </div>
    </div>
    
    <!-- Recent POs -->
    <div class="po-recent" id="recentTable"></div>
</div>

<?php
/* ── xcrud Table (PRESERVED 100%) ── */
$userid = $_SESSION['UserID'];
$userfullname = $_SESSION['UsersRealName'];
$timenow = date('Y-m-d H:i:s');

include('xcrud/xcrud.php');
$purchaseorders = Xcrud::get_instance();
$purchaseorders->table('purchorders');

if ($userid =='schand' ||$userid =='stephanie' || $userid =='losa' ||$userid == 'manueli'){
    $purchaseorders->where('department=',array('6','8','29'));
}
if ($userid == 'nisha' ||$userid == 'douglas' ||$userid == 'akumar' ){
    $purchaseorders->where('department=',array('7','29'));
    $purchaseorders->unset_edit();
}
if ($userid == 'lusi' ||$userid == 'mike' || $userid =='riaz'  ){
    $purchaseorders->where('department', array('2','10','21','29'));
    $purchaseorders->unset_edit();
}
if ($userid =='mosheed' || $userid =='ronil' || $userid=='sala' || $userid=='roneelp' || $userid=='saula' || $userid=='vineshkumar' ||$userid =='menani'){
    $purchaseorders->where('department', array('1','2','6','7','9','10','13','14','16','19','23','28','29'));
    $purchaseorders->unset_edit();
}
if ($userid =='maraia' ||$userid == 'ashil' || $userid =='vani'|| $userid =='serge'){
    $purchaseorders->where('department=',array('18','19','28','29'));
    $purchaseorders->unset_edit();
}
if ($userid =='rajnesh'){
    $purchaseorders->where('department=',array('3','29'));
    $purchaseorders->unset_edit();
}
if ($userid =='rowen' || $userid =='rramlu'){
    $purchaseorders->where('department', array('8','21','29'));
    $purchaseorders->unset_edit();
}
if ($userid=='asenacacagi' || $userid=='liti' || $userid=='maca' || $userid=='ronald' || $userid=='seni' ||$userid=='tarusila' || $userid=='jtukana' || $userid=='wili' || $userid=='mairewa'|| $userid=='lani'||$userid =='saula' ||$userid =='menani' ){
    $purchaseorders->where('department', array('2','29'));
}
if ($userid=='annie'||$userid=='salata'||$userid=='jokaveti'||$userid=='auliasi'||$userid=='alumita'||$userid=='alisi'||$userid=='asenaca'||$userid=='lavenia'||$userid=='marenda'||$userid=='kalesim' ||$userid=='ilimo' ||$userid=='jpenjueli' || $userid == 'saula' || $userid == 'marica' ||$userid =='semi'){
    $purchaseorders->where('department=',array('1','3','29'));
}
if ($userid == 'mere' ||$userid == 'zubia' ||$userid == 'eugene' ||$userid =='sureta' ||$userid =='crispus' ||$userid =='lina' ){
    $purchaseorders->where('department=',array('9','11','29'));
}
if ($userid == 'mkhan' ||$userid == 'pchand' ||$userid == 'walesi' ){
    $purchaseorders->where('department=',array('22','23','29'));
}

$purchaseorders->unset_add();
$purchaseorders->unset_remove();
$purchaseorders->order_by('orderno','desc');
$purchaseorders->fields('orderno,total_vep,supplierno,orddate,initiator,requisitionno,contact,suppliercontact,status,stat_comment,department,authorised_by,depart_authorised_by,comments,deliverydate',false);
$purchaseorders->columns('orderno,total_vep,supplierno,orddate,initiator,requisitionno,contact,suppliercontact,status,stat_comment,department,authorised_by,depart_authorised_by,comments,deliverydate',false);
$purchaseorders->table_name('Purchase Orders Detailed');
$purchaseorders->unset_add();
$purchaseorders->unset_remove();
$purchaseorders->column_pattern('orderno', '<a href="#" class="xcrud-action" data-task="view" data-primary="{orderno}">{value}</a>');
$purchaseorders->relation('supplierno','suppliers','supplierid','suppname');
$purchaseorders->disabled('status,stat_comment');
$purchaseorders->sum('total_vep');
$purchaseorders->relation('department','department','departmentid','departmentname');
$purchaseorders->button('SupplierInvoice.php?SupplierID={supplierno}&orderno{orderno}', 'Supp Invoice','glyphicon glyphicon-repeat','westpac');

$purchaseordersdetails = $purchaseorders->nested_table('Item Line Details','orderno','purchorderdetails','orderno');
$purchaseordersdetails->unset_add();
$purchaseordersdetails->unset_remove();
$purchaseordersdetails->table_name('Line item Details');
$purchaseordersdetails->fields('itemdescription,taxrate,unitprice,quantityord,quantityrecd,total,oldglcode,jobref,deliverydate,completed',false);
$purchaseordersdetails->columns('itemdescription,taxrate,unitprice,quantityord,quantityrecd,total,oldglcode,jobref,deliverydate,completed',false);
$purchaseordersdetails->subselect('total','{unitprice}*{quantityord}');
$purchaseordersdetails->sum('total');
$purchaseordersdetails->change_type('total,unitprice', 'price', '0', array('prefix'=>'$','decimals'=>'2'));
$purchaseordersdetails->relation('oldglcode','oldglcode','oldglcode','oldglcode');
$purchaseordersdetails->relation('glcode','chartmaster','accountcode',array('accountname','accountcode'));
$purchaseordersdetails->relation('tags','tags','tagref','tagdescription');

$attachments = $purchaseorders->nested_table('Attachments','orderno','purchorder_attachements','orderno');
$attachments->change_type('photo', 'image', '', array('thumbs' => 
    array(
        array('width' => '200', 'height' => '200', 'marker' => '_th'),
        array('width' => 50, 'height' => 50, 'crop' => true, 'folder' => 'thumbs')
    )));
$attachments->change_type('file', 'file', '', array('not_rename'=>true));

$split = $purchaseorders->nested_table('Split Cost','orderno','purchorder_split','orderno');
$split->relation('glcode','oldglcode','id',array('oldglcode','name'),array('type'=>'Profit & Loss'));
$split->relation('jobno','projectdetails','wip_expense',array('wip_expense','project_name','projectid'));
$split->label('amount',"Amount(Take VIP Value ONLY)");
$split->label('jobno',"WIP Expense/Job Related");
$split->disabled('posted');
$split->before_update('checksplit','functionpurchaseorders.php');
$split->before_insert('checksplit','functionpurchaseorders.php');

echo $purchaseorders->render();

echo '</div></div>';
?>
</div><!-- end po-app -->

<script>
var poCharts = {};
var monthNames = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var palette = ['#2AABB3','#1890FF','#52C41A','#FAAD14','#FF4D4F','#722ED1','#13C2C2','#FA541C'];

function fmt(n) { return '$' + Number(n).toLocaleString('en-US',{minimumFractionDigits:0,maximumFractionDigits:0}); }
function fmtK(n) { return n>=1000000 ? '$'+(n/1000000).toFixed(1)+'M' : n>=1000 ? '$'+(n/1000).toFixed(0)+'K' : '$'+n; }
function pctChange(cy,py) { if(!py||py==0) return {val:0,dir:'flat'}; var p=((cy-py)/py*100).toFixed(1); return {val:Math.abs(p),dir:p>0?'up':p<0?'down':'flat'}; }

function buildKPI(id, icon, iconCls, value, label, delta, borderColor) {
    var dHtml = '';
    if (delta) {
        var cls = delta.dir==='up'?'kd-up':delta.dir==='down'?'kd-down':'kd-flat';
        var arrow = delta.dir==='up'?'<i class="fas fa-arrow-up" style="font-size:9px"></i>':delta.dir==='down'?'<i class="fas fa-arrow-down" style="font-size:9px"></i>':'';
        dHtml = '<div class="kd '+cls+'">'+arrow+' '+delta.val+'% vs PY</div>';
    }
    return '<div class="po-kpi" style="border-left-color:'+borderColor+'"><div class="po-kpi-top"><div class="po-kpi-icon '+iconCls+'"><i class="fas '+icon+'"></i></div></div><div class="kv">'+value+'</div><div class="kl">'+label+'</div>'+dHtml+'</div>';
}

function renderDashboard(d) {
    // Banner
    document.getElementById('bTotal').textContent = d.total_cy.toLocaleString();
    document.getElementById('bValue').textContent = fmtK(d.ytd_val_cy);
    document.getElementById('bPending').textContent = d.pending.toLocaleString();
    document.getElementById('bSuppliers').textContent = d.unique_suppliers.toLocaleString();
    
    // KPI Row 1
    var pctTotal = pctChange(d.total_cy, d.total_py);
    var pctVal = pctChange(d.ytd_val_cy, d.ytd_val_py);
    document.getElementById('kpiRow1').innerHTML = 
        buildKPI('k1','fa-file-invoice-dollar','ic-teal', d.total_cy.toLocaleString(), d.cur_year+' Total POs', pctTotal, '#2AABB3') +
        buildKPI('k2','fa-dollar-sign','ic-green', fmtK(d.ytd_val_cy), d.cur_year+' YTD Value', pctVal, '#52C41A') +
        buildKPI('k3','fa-calendar-day','ic-blue', d.month_cnt.toLocaleString(), 'This Month Orders', null, '#1890FF') +
        buildKPI('k4','fa-receipt','ic-purple', fmtK(d.month_val), 'This Month Value', null, '#722ED1');
    
    // KPI Row 2
    document.getElementById('kpiRow2').innerHTML = 
        buildKPI('k5','fa-clock','ic-orange', d.pending.toLocaleString(), 'Pending Approval', null, '#FAAD14') +
        buildKPI('k6','fa-check-double','ic-green', d.authorised.toLocaleString(), 'Authorised / Printed', null, '#52C41A') +
        buildKPI('k7','fa-chart-bar','ic-teal', fmtK(d.avg_po_val), 'Average PO Value', null, '#2AABB3') +
        buildKPI('k8','fa-box-open','ic-red', fmtK(d.outstanding_val), 'Outstanding Value', null, '#FF4D4F');
    
    // Chart 1: Monthly Value Trend (CY vs PY line)
    var cyVals = new Array(12).fill(0), pyVals = new Array(12).fill(0);
    d.monthly_trend.forEach(function(r){ cyVals[parseInt(r.m)-1] = parseFloat(r.val); });
    d.monthly_trend_py.forEach(function(r){ pyVals[parseInt(r.m)-1] = parseFloat(r.val); });
    
    poCharts.trend = new Chart(document.getElementById('chartTrend'), {
        type:'line', data:{
            labels: monthNames,
            datasets:[
                {label:d.cur_year+' Value',data:cyVals,borderColor:'#2AABB3',backgroundColor:'rgba(42,171,179,0.1)',fill:true,tension:0.4,borderWidth:2,pointRadius:3,pointBackgroundColor:'#2AABB3'},
                {label:d.prev_year+' Value',data:pyVals,borderColor:'#D1D5DB',backgroundColor:'transparent',borderDash:[5,3],tension:0.4,borderWidth:1.5,pointRadius:2,pointBackgroundColor:'#D1D5DB'}
            ]
        }, options:{responsive:true,maintainAspectRatio:false,animation:false,plugins:{legend:{position:'top',labels:{font:{size:10,family:'Poppins'},boxWidth:12,padding:8}}},scales:{y:{ticks:{callback:function(v){return fmtK(v)},font:{size:10,family:'Poppins'}},grid:{color:'#F0F0F0'}},x:{ticks:{font:{size:10,family:'Poppins'}},grid:{display:false}}}}
    });
    
    // Chart 2: Monthly Count
    var cyCounts = new Array(12).fill(0), pyCounts = new Array(12).fill(0);
    d.monthly_trend.forEach(function(r){ cyCounts[parseInt(r.m)-1] = parseInt(r.cnt); });
    d.monthly_trend_py.forEach(function(r){ pyCounts[parseInt(r.m)-1] = parseInt(r.cnt); });
    
    poCharts.count = new Chart(document.getElementById('chartCount'), {
        type:'bar', data:{
            labels: monthNames,
            datasets:[
                {label:d.cur_year,data:cyCounts,backgroundColor:'rgba(42,171,179,0.7)',borderRadius:4,maxBarThickness:20},
                {label:d.prev_year,data:pyCounts,backgroundColor:'rgba(209,213,219,0.5)',borderRadius:4,maxBarThickness:20}
            ]
        }, options:{responsive:true,maintainAspectRatio:false,animation:false,plugins:{legend:{position:'top',labels:{font:{size:10,family:'Poppins'},boxWidth:12,padding:8}}},scales:{y:{ticks:{font:{size:10,family:'Poppins'}},grid:{color:'#F0F0F0'}},x:{ticks:{font:{size:10,family:'Poppins'}},grid:{display:false}}}}
    });
    
    // Chart 3: Top Suppliers (horizontal bar)
    var suppLabels=[], suppVals=[];
    d.top_suppliers.forEach(function(r){ suppLabels.push(r.suppname.substring(0,25)); suppVals.push(parseFloat(r.val)); });
    
    poCharts.suppliers = new Chart(document.getElementById('chartSuppliers'), {
        type:'bar', data:{
            labels:suppLabels,
            datasets:[{data:suppVals,backgroundColor:palette.slice(0,suppVals.length),borderRadius:4,maxBarThickness:18}]
        }, options:{indexAxis:'y',responsive:true,maintainAspectRatio:false,animation:false,plugins:{legend:{display:false}},scales:{x:{ticks:{callback:function(v){return fmtK(v)},font:{size:10,family:'Poppins'}},grid:{color:'#F0F0F0'}},y:{ticks:{font:{size:10,family:'Poppins'}},grid:{display:false}}}}
    });
    
    // Chart 4: Department Doughnut
    var deptLabels=[], deptVals=[];
    d.dept_breakdown.forEach(function(r){ deptLabels.push(r.departmentname.substring(0,20)); deptVals.push(parseFloat(r.val)); });
    
    poCharts.dept = new Chart(document.getElementById('chartDept'), {
        type:'doughnut', data:{
            labels:deptLabels,
            datasets:[{data:deptVals,backgroundColor:palette.slice(0,deptVals.length),borderWidth:1,hoverOffset:6}]
        }, options:{responsive:true,maintainAspectRatio:false,animation:false,cutout:'60%',plugins:{legend:{position:'right',labels:{font:{size:10,family:'Poppins'},boxWidth:10,padding:6}}}}
    });
    
    // Chart 5: Status Doughnut
    var statusColors = {'Pending':'#FAAD14','Authorised':'#52C41A','Printed':'#1890FF','Cancelled':'#FF4D4F','Rejected':'#FF7A45','DepartmentalAuthorised':'#722ED1'};
    var stLabels=[], stVals=[], stColors=[];
    d.status_dist.forEach(function(r){ stLabels.push(r.status); stVals.push(parseInt(r.cnt)); stColors.push(statusColors[r.status]||'#D1D5DB'); });
    
    poCharts.status = new Chart(document.getElementById('chartStatus'), {
        type:'doughnut', data:{
            labels:stLabels,
            datasets:[{data:stVals,backgroundColor:stColors,borderWidth:1,hoverOffset:6}]
        }, options:{responsive:true,maintainAspectRatio:false,animation:false,cutout:'60%',plugins:{legend:{position:'right',labels:{font:{size:10,family:'Poppins'},boxWidth:10,padding:6}}}}
    });
    
    // Chart 6: Top Items (horizontal bar)
    var itemLabels=[], itemVals=[];
    d.top_items.forEach(function(r){ itemLabels.push(r.itemdescription.substring(0,30)); itemVals.push(parseFloat(r.val)); });
    
    poCharts.items = new Chart(document.getElementById('chartItems'), {
        type:'bar', data:{
            labels:itemLabels,
            datasets:[{data:itemVals,backgroundColor:'rgba(42,171,179,0.65)',borderRadius:4,maxBarThickness:16}]
        }, options:{indexAxis:'y',responsive:true,maintainAspectRatio:false,animation:false,plugins:{legend:{display:false}},scales:{x:{ticks:{callback:function(v){return fmtK(v)},font:{size:9,family:'Poppins'}},grid:{color:'#F0F0F0'}},y:{ticks:{font:{size:9,family:'Poppins'}},grid:{display:false}}}}
    });
    
    // Recent POs Table
    var html = '<div class="po-recent-head"><div class="po-recent-head-left"><i class="fas fa-history"></i> Recent Purchase Orders ('+d.cur_year+')</div></div>';
    html += '<table><thead><tr><th>Order #</th><th>Date</th><th>Supplier</th><th>Department</th><th>Initiator</th><th>Value</th><th>Status</th></tr></thead><tbody>';
    d.recent_pos.forEach(function(r){
        var sc = r.status.toLowerCase().replace(/\s/g,'');
        html += '<tr><td style="font-weight:600;color:#2AABB3;">#'+r.orderno+'</td><td>'+r.orddate+'</td><td>'+r.suppname+'</td><td>'+r.departmentname+'</td><td>'+r.initiator+'</td><td style="text-align:right;font-weight:600;">'+fmt(r.val)+'</td><td><span class="po-sbadge po-sb-'+sc+'">'+r.status+'</span></td></tr>';
    });
    html += '</tbody></table>';
    document.getElementById('recentTable').innerHTML = html;
}

function togglePoDash() {
    var w = document.getElementById('poDash'), t = document.getElementById('poToggle');
    if (w.classList.contains('collapsed')) { w.classList.remove('collapsed'); t.classList.remove('collapsed'); localStorage.setItem('poDashCollapsed','false'); }
    else { w.classList.add('collapsed'); t.classList.add('collapsed'); localStorage.setItem('poDashCollapsed','true'); }
}

(function(){
    if (localStorage.getItem('poDashCollapsed')==='true') {
        document.getElementById('poDash').classList.add('collapsed');
        document.getElementById('poToggle').classList.add('collapsed');
    }
    
    var startTime = Date.now();
    var timerEl = document.getElementById('poLoadTimer');
    var timerInt = setInterval(function(){
        var elapsed = ((Date.now()-startTime)/1000).toFixed(1);
        if(timerEl) timerEl.textContent = 'Loading data... '+elapsed+'s';
    }, 100);
    
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'PurchaseOrders.php?api=dashboard', true);
    xhr.onreadystatechange = function(){
        if(xhr.readyState===4){
            clearInterval(timerInt);
            var modal = document.getElementById('poLoadingModal');
            if(modal) { modal.style.opacity='0'; modal.style.transition='opacity 0.3s'; setTimeout(function(){ modal.style.display='none'; },300); }
            if(xhr.status===200){
                try { var data = JSON.parse(xhr.responseText); renderDashboard(data); }
                catch(e){ console.error('Dashboard JSON parse error',e); }
            }
        }
    };
    xhr.send();
})();
</script>

<?php include('includes/footer.inc'); ?>