<?php
/* PO_SelectOSPurchOrder.php - Enhanced with full PO dashboard + outstanding orders table */
error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity=0;

/* ── API Mode: Dashboard Data ── */
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 = $dbc->real_escape_string($_SESSION['UserID']);
    $curYear = date('Y');
    $curMonth = date('m');
    $prevYear = $curYear - 1;
    
    $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),'amelia'=>array(22,23,29)
    );
    
    $df = '';
    if (isset($deptMap[$_SESSION['UserID']])) {
        $d = $deptMap[$_SESSION['UserID']];
        if ($d !== 'ALL') { $ids = implode(',', array_map('intval', $d)); $df = " AND po.department IN ($ids)"; }
    }
    $locJoin = "INNER JOIN locationusers lu ON lu.loccode=po.intostocklocation AND lu.userid='$userid' AND lu.canview=1";
    $data = array();
    
    /* YEARLY */
    $r=$dbc->query("SELECT COUNT(*) AS cnt FROM purchorders po WHERE YEAR(po.orddate)='$curYear' $df"); $data['total_cy']=($r&&$row=$r->fetch_assoc())?(int)$row['cnt']:0;
    $r=$dbc->query("SELECT COUNT(*) AS cnt FROM purchorders po WHERE YEAR(po.orddate)='$prevYear' $df"); $data['total_py']=($r&&$row=$r->fetch_assoc())?(int)$row['cnt']:0;
    $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' $df"); $data['ytd_val_cy']=($r&&$row=$r->fetch_assoc())?round((float)$row['val'],2):0;
    $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' $df"); $data['ytd_val_py']=($r&&$row=$r->fetch_assoc())?round((float)$row['val'],2):0;
    $r=$dbc->query("SELECT COUNT(*) AS cnt FROM purchorders po WHERE YEAR(po.orddate)='$curYear' AND MONTH(po.orddate)='$curMonth' $df"); $data['month_cnt']=($r&&$row=$r->fetch_assoc())?(int)$row['cnt']:0;
    $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' $df"); $data['month_val']=($r&&$row=$r->fetch_assoc())?round((float)$row['val'],2):0;
    $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' $df GROUP BY po.orderno) sub"); $data['avg_po_val']=($r&&$row=$r->fetch_assoc())?round((float)$row['avgval'],2):0;
    $r=$dbc->query("SELECT COUNT(DISTINCT po.supplierno) AS cnt FROM purchorders po WHERE YEAR(po.orddate)='$curYear' $df"); $data['unique_suppliers']=($r&&$row=$r->fetch_assoc())?(int)$row['cnt']:0;
    
    /* OUTSTANDING */
    $osBase = "FROM purchorders po INNER JOIN purchorderdetails pod ON po.orderno=pod.orderno $locJoin WHERE pod.completed=0 $df";
    $r=$dbc->query("SELECT COUNT(DISTINCT po.orderno) AS cnt $osBase"); $data['os_total']=($r&&$row=$r->fetch_assoc())?(int)$row['cnt']:0;
    $r=$dbc->query("SELECT COUNT(DISTINCT po.orderno) AS cnt $osBase AND po.status='Pending'"); $data['os_pending']=($r&&$row=$r->fetch_assoc())?(int)$row['cnt']:0;
    $r=$dbc->query("SELECT COUNT(DISTINCT po.orderno) AS cnt $osBase AND (po.status='Authorised' OR po.status='Printed')"); $data['os_auth']=($r&&$row=$r->fetch_assoc())?(int)$row['cnt']:0;
    $r=$dbc->query("SELECT COUNT(DISTINCT po.orderno) AS cnt $osBase AND po.status='Printed'"); $data['os_printed']=($r&&$row=$r->fetch_assoc())?(int)$row['cnt']:0;
    $r=$dbc->query("SELECT COALESCE(SUM(pod.unitprice*(pod.quantityord-pod.quantityrecd)),0) AS val $osBase"); $data['os_val']=($r&&$row=$r->fetch_assoc())?round((float)$row['val'],2):0;
    $r=$dbc->query("SELECT DATEDIFF(CURDATE(),MIN(po.orddate)) AS days $osBase"); $data['os_oldest_days']=($r&&$row=$r->fetch_assoc())?(int)$row['days']:0;
    $r=$dbc->query("SELECT COUNT(DISTINCT po.orderno) AS cnt $osBase AND YEARWEEK(po.orddate,1)=YEARWEEK(CURDATE(),1)"); $data['os_this_week']=($r&&$row=$r->fetch_assoc())?(int)$row['cnt']:0;
    
    /* CHARTS */
    $arr=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' $df GROUP BY MONTH(po.orddate) ORDER BY m");if($r){while($row=$r->fetch_assoc()){$arr[]=$row;}}$data['monthly_trend']=$arr;
    $arr=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' $df GROUP BY MONTH(po.orddate) ORDER BY m");if($r){while($row=$r->fetch_assoc()){$arr[]=$row;}}$data['monthly_trend_py']=$arr;
    $arr=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' $df GROUP BY s.suppname ORDER BY val DESC LIMIT 6");if($r){while($row=$r->fetch_assoc()){$arr[]=$row;}}$data['top_suppliers']=$arr;
    $arr=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' $df GROUP BY d.departmentname ORDER BY val DESC LIMIT 8");if($r){while($row=$r->fetch_assoc()){$arr[]=$row;}}$data['dept_breakdown']=$arr;
    $arr=array();$r=$dbc->query("SELECT po.status,COUNT(*) AS cnt FROM purchorders po WHERE YEAR(po.orddate)='$curYear' $df GROUP BY po.status ORDER BY cnt DESC");if($r){while($row=$r->fetch_assoc()){$arr[]=$row;}}$data['status_dist']=$arr;
    $arr=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!='' $df GROUP BY pod.itemdescription ORDER BY val DESC LIMIT 8");if($r){while($row=$r->fetch_assoc()){$arr[]=$row;}}$data['top_items']=$arr;
    $data['aging']=array('d30'=>0,'d60'=>0,'d90'=>0,'d90p'=>0);
    $r=$dbc->query("SELECT SUM(CASE WHEN DATEDIFF(CURDATE(),po.orddate)<=30 THEN pod.unitprice*(pod.quantityord-pod.quantityrecd) ELSE 0 END) AS d30,SUM(CASE WHEN DATEDIFF(CURDATE(),po.orddate) BETWEEN 31 AND 60 THEN pod.unitprice*(pod.quantityord-pod.quantityrecd) ELSE 0 END) AS d60,SUM(CASE WHEN DATEDIFF(CURDATE(),po.orddate) BETWEEN 61 AND 90 THEN pod.unitprice*(pod.quantityord-pod.quantityrecd) ELSE 0 END) AS d90,SUM(CASE WHEN DATEDIFF(CURDATE(),po.orddate)>90 THEN pod.unitprice*(pod.quantityord-pod.quantityrecd) ELSE 0 END) AS d90p $osBase");
    if($r&&$row=$r->fetch_assoc()){$data['aging']=array('d30'=>round((float)$row['d30'],0),'d60'=>round((float)$row['d60'],0),'d90'=>round((float)$row['d90'],0),'d90p'=>round((float)$row['d90p'],0));}
    $arr=array();$r=$dbc->query("SELECT s.suppname,COALESCE(SUM(pod.unitprice*(pod.quantityord-pod.quantityrecd)),0) AS val,COUNT(DISTINCT po.orderno) AS cnt $osBase INNER JOIN suppliers s ON po.supplierno=s.supplierid GROUP BY s.suppname ORDER BY val DESC LIMIT 5");if($r){while($row=$r->fetch_assoc()){$arr[]=$row;}}$data['os_top_suppliers']=$arr;
    $arr=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' $df GROUP BY po.orderno ORDER BY po.orderno DESC LIMIT 5");if($r){while($row=$r->fetch_assoc()){$arr[]=$row;}}$data['recent_pos']=$arr;
    $data['cur_year']=(int)$curYear;$data['prev_year']=(int)$prevYear;$data['cur_month_name']=date('F Y');
    $dbc->close();echo json_encode($data);exit;
}

/* ── Normal Page Render ── */
include('includes/session.inc');
$Title=_('Outstanding Purchase Orders');
include('includes/newheader.php');
include('includes/DefinePOClass.php');
include('includes/SQL_CommonFunctions.inc');
$userid = $_SESSION['UserID'];

$deptMap = array(
    'admin'=>'ALL','sharukh'=>'ALL','ravinesh'=>'ALL','eseta'=>'ALL','jtukana'=>'ALL','shiv'=>'ALL','priyakumar'=>'ALL',
    'nisha'=>array(7,29),'douglas'=>array(7,29),'akumar'=>array(7,29),
    'maraia'=>array(18,19,29),'ashil'=>array(18,19,29),'vani'=>array(18,19,29),'serge'=>array(18,19,29),
    'schand'=>array(6,8,29),'stephanie'=>array(6,8,29),'losa'=>array(6,8,29),'manueli'=>array(6,8,29),
    'lusi'=>array(2,10,21,29),'mike'=>array(2,10,21,29),'riaz'=>array(2,10,21,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),
    '11113'=>array(1,3,29),'marica'=>array(1,3,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),'menani'=>array(2,29),
    'mkhan'=>array(22,23),'pchand'=>array(22,23),'walesi'=>array(22,23),'amelia'=>array(22,23),
    'mere'=>array(9,11),'zubia'=>array(9,11),'lina'=>array(9,11),'crispus'=>array(9,11),
    'mosheed'=>array(2,7,10,13,14,16,18,19,23,28,29),'roneelp'=>array(2,7,10,13,14,16,18,19,23,28,29),
    'sala'=>array(2,7,10,13,14,16,18,19,23,28,29),'saula'=>array(2,7,10,13,14,16,18,19,23,28,29),
    'ronil'=>array(2,7,10,13,14,16,18,19,23,28,29),'vineshkumar'=>array(2,7,10,13,14,16,18,19,23,28,29),
    'rajnesh'=>array(3),'rowen'=>array(8,21),'rramlu'=>array(8,21)
);
$userAllowed=false;$deptWhere='';
if(isset($deptMap[$userid])){$userAllowed=true;$userDepts=$deptMap[$userid];if($userDepts==='ALL'){$deptWhere='';}else{$c=array();foreach($userDepts as $d){$c[]="purchorders.department=".(int)$d;}$deptWhere=" AND (".implode(" OR ",$c).")";}}
if(!$userAllowed){echo '<div style="padding:40px;text-align:center;font-family:Poppins,sans-serif;color:#FF4D4F;font-size:16px;font-weight:600;"><i class="fas fa-lock" style="font-size:48px;margin-bottom:16px;display:block;color:#D1D5DB;"></i>Not Authorised to view Purchase Orders</div>';include('includes/footer.inc');exit;}
?>

<!-- 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>
.po-wrap *{box-sizing:border-box}.po-wrap{font-family:'Poppins',-apple-system,BlinkMacSystemFont,sans-serif;color:#1F2937;max-width:1440px;margin:0 auto;padding:0 20px 40px}
.po-banner{background:linear-gradient(135deg,#1E8F96 0%,#2AABB3 50%,#35C4CD 100%);border-radius:16px;padding:26px 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:0 0 4px;letter-spacing:-0.3px}.po-banner p{font-size:13px;opacity:0.85;margin:0;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}
.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.5s ease,opacity 0.3s;max-height:2400px;opacity:1}.po-dash.collapsed{max-height:0;opacity:0}
.po-section-hd{display:flex;align-items:center;gap:8px;font-size:13px;font-weight:600;color:#1F2937;margin:18px 0 10px;padding-bottom:8px;border-bottom:2px solid #E6F7F8}
.po-section-hd i{color:#2AABB3;font-size:14px}.po-section-hd .po-badge{font-size:10px;font-weight:600;padding:2px 8px;border-radius:10px;margin-left:6px}
.po-badge-teal{background:#E6F7F8;color:#1E8F96}.po-badge-orange{background:#FFF4E6;color:#AD6800}
.po-kpi-row{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:14px}
.po-kpi{background:#fff;border-radius:12px;padding:14px 16px;border-left:4px solid #2AABB3;box-shadow:0 1px 6px rgba(0,0,0,0.05);transition:transform 0.2s,box-shadow 0.2s}
.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:6px}
.po-kpi-icon{width:34px;height:34px;border-radius:9px;display:flex;align-items:center;justify-content:center;font-size:14px}
.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:2px}
.po-kpi .ks{font-size:10px;color:#9CA3AF;margin-top:2px}
.po-kpi .kd{font-size:10px;margin-top:3px;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}
.po-charts{display:grid;grid-template-columns:repeat(2,1fr);gap:12px;margin-bottom:14px}
.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-hd{padding:10px 14px;border-bottom:1px solid #F0F0F0;display:flex;align-items:center;gap:8px;font-size:12px;font-weight:600;color:#1F2937}
.po-chart-hd i{color:#2AABB3;font-size:13px}.po-chart-bd{padding:12px 14px}.po-chart-bd canvas{max-height:190px!important}
.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:14px}
.po-recent-head{padding:10px 14px;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:12px;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:10px;font-weight:600;text-transform:uppercase;letter-spacing:0.4px;color:#6B7280;padding:8px 12px;text-align:left;border-bottom:1px solid #E5E7EB}
.po-recent td{font-size:11px;padding:8px 12px;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}
.sb-pending{background:#FFF4E6;color:#AD6800}.sb-authorised,.sb-printed{background:#E8F8E8;color:#389E0D}.sb-cancelled,.sb-rejected{background:#FFF1F0;color:#CF1322}.sb-departmentalauthorised{background:#E8F4FD;color:#096DD9}
.po-wrap table.selection{width:100%;border-collapse:collapse;margin-bottom:12px}.po-wrap table.selection td{padding:8px 6px;font-size:13px;vertical-align:middle}
.po-wrap input[type="text"],.po-wrap select{height:38px;border:1.5px solid #D1D5DB;border-radius:8px;font-family:'Poppins',sans-serif;font-size:13px;padding:0 12px;outline:none;transition:border-color 0.2s}
.po-wrap input[type="text"]:focus,.po-wrap select:focus{border-color:#2AABB3;box-shadow:0 0 0 3px rgba(42,171,179,0.12)}
.po-wrap input[type="submit"]{background:linear-gradient(135deg,#2AABB3,#1E8F96);color:#fff;border:none;border-radius:8px;font-family:'Poppins',sans-serif;font-weight:600;font-size:13px;padding:9px 20px;cursor:pointer;transition:all 0.2s;box-shadow:0 2px 8px rgba(42,171,179,0.3)}
.po-wrap input[type="submit"]:hover{background:linear-gradient(135deg,#1E8F96,#187278);transform:translateY(-1px);box-shadow:0 4px 16px rgba(42,171,179,0.4)}
.po-results-card{background:#fff;border-radius:12px;box-shadow:0 1px 8px rgba(0,0,0,0.06);border:1px solid #E5E7EB;overflow:hidden;margin-top:16px}
.po-results-head{padding:14px 20px;border-bottom:1px solid #F0F0F0;display:flex;align-items:center;justify-content:space-between;background:#FAFBFC}
.po-results-head-left{display:flex;align-items:center;gap:10px;font-weight:600;font-size:14px;color:#1F2937}.po-results-head-left i{color:#2AABB3}
.po-results-count{font-size:12px;color:#6B7280;font-weight:500;background:#F3F4F6;padding:4px 12px;border-radius:20px}
.po-wrap table.po-table{width:100%;border-collapse:collapse}
.po-wrap table.po-table thead th{background:linear-gradient(135deg,#1E8F96,#2AABB3);color:#fff;font-family:'Poppins',sans-serif;font-weight:600;font-size:11px;text-transform:uppercase;letter-spacing:0.5px;padding:12px 10px;border:none;border-right:1px solid rgba(255,255,255,0.12);white-space:nowrap;text-align:left}
.po-wrap table.po-table thead th:last-child{border-right:none}.po-wrap table.po-table thead th a{color:#fff;text-decoration:none}
.po-wrap table.po-table tbody td{font-family:'Poppins',sans-serif;font-size:12px;padding:10px;border-bottom:1px solid #F0F0F0;color:#374151;vertical-align:middle}
.po-wrap table.po-table tbody tr:nth-child(even){background:#FAFBFC}.po-wrap table.po-table tbody tr:nth-child(odd){background:#fff}.po-wrap table.po-table tbody tr:hover{background:#F0FAFB}
.po-status{display:inline-block;padding:3px 10px;border-radius:10px;font-size:11px;font-weight:600;white-space:nowrap}
.po-status-pending{background:#FFF4E6;color:#AD6800}.po-status-authorised,.po-status-printed{background:#E8F8E8;color:#389E0D}
.po-status-cancelled,.po-status-rejected{background:#FFF1F0;color:#CF1322}.po-status-departmentalauthorised{background:#E8F4FD;color:#096DD9}
.po-order-link{font-weight:600;color:#2AABB3;text-decoration:none;background:#E6F7F8;padding:3px 10px;border-radius:6px}.po-order-link:hover{background:#D0F0F2;color:#187278}
.po-action{display:inline-block;padding:4px 10px;border-radius:6px;font-size:11px;font-weight:600;text-decoration:none;transition:all 0.2s;border:1px solid #E5E7EB;background:#fff;color:#374151;white-space:nowrap}
.po-action:hover{background:#E6F7F8;border-color:#2AABB3;color:#1E8F96}.po-action-print{border-left:3px solid #1890FF}.po-action-receive{border-left:3px solid #52C41A}
.po-pagination{display:flex;align-items:center;justify-content:center;gap:4px;padding:16px 20px;border-top:1px solid #F0F0F0}
.po-pagination a,.po-pagination span{display:inline-flex;align-items:center;justify-content:center;min-width:34px;height:34px;border-radius:8px;font-family:'Poppins',sans-serif;font-size:12px;font-weight:600;text-decoration:none;border:1px solid #E5E7EB;color:#374151;background:#fff;transition:all 0.2s}
.po-pagination a:hover{background:#E6F7F8;border-color:#2AABB3;color:#1E8F96}.po-pagination .current{background:linear-gradient(135deg,#2AABB3,#1E8F96);color:#fff;border-color:#1E8F96}
.po-pagination .disabled{opacity:0.4;pointer-events:none}.po-pagination .page-info{border:none;font-weight:400;color:#6B7280;font-size:12px;min-width:auto;padding:0 8px}
.po-add-btn{display:inline-flex;align-items:center;gap:8px;background:linear-gradient(135deg,#2AABB3,#1E8F96);color:#fff;border:none;border-radius:8px;font-family:'Poppins',sans-serif;font-weight:600;font-size:13px;padding:10px 20px;text-decoration:none;box-shadow:0 2px 8px rgba(42,171,179,0.3);transition:all 0.2s;margin-bottom:16px}
.po-add-btn:hover{background:linear-gradient(135deg,#1E8F96,#187278);color:#fff;transform:translateY(-1px)}
@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-wrap">
<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>Outstanding Purchase Orders</span></div>
    <h1><i class="fas fa-file-invoice" style="margin-right:10px;opacity:0.9;"></i>Outstanding Purchase Orders</h1>
    <p>Search, review, and manage open purchase orders with real-time analytics</p>
    <div class="po-banner-row">
        <div class="po-banner-stat"><div class="sv" id="bOS">--</div><div class="sl">Outstanding</div></div>
        <div class="po-banner-stat"><div class="sv" id="bOSVal">--</div><div class="sl">Outstanding Value</div></div>
        <div class="po-banner-stat"><div class="sv" id="bYTD">--</div><div class="sl">YTD POs</div></div>
        <div class="po-banner-stat"><div class="sv" id="bYTDVal">--</div><div class="sl">YTD Value</div></div>
        <div class="po-banner-stat"><div class="sv" id="bSupp">--</div><div class="sl">Active Suppliers</div></div>
    </div>
</div>
<div class="po-toggle" id="poToggle" onclick="togglePoDash()"><i class="fas fa-chevron-down chv"></i><span>Dashboard Analytics</span></div>
<div class="po-dash" id="poDash">
    <div class="po-section-hd"><i class="fas fa-chart-line"></i> <span id="yearLabel"></span> Purchase Order Insights <span class="po-badge po-badge-teal">Year to Date</span></div>
    <div class="po-kpi-row" id="kpiYear"></div>
    <div class="po-charts">
        <div class="po-chart-card"><div class="po-chart-hd"><i class="fas fa-chart-area"></i> Monthly PO Value Trend</div><div class="po-chart-bd"><canvas id="chTrend"></canvas></div></div>
        <div class="po-chart-card"><div class="po-chart-hd"><i class="fas fa-chart-bar"></i> Monthly PO Count</div><div class="po-chart-bd"><canvas id="chCount"></canvas></div></div>
    </div>
    <div class="po-charts">
        <div class="po-chart-card"><div class="po-chart-hd"><i class="fas fa-building"></i> Top Suppliers by Value</div><div class="po-chart-bd"><canvas id="chSupp"></canvas></div></div>
        <div class="po-chart-card"><div class="po-chart-hd"><i class="fas fa-sitemap"></i> Department Spend</div><div class="po-chart-bd"><canvas id="chDept"></canvas></div></div>
    </div>
    <div class="po-charts">
        <div class="po-chart-card"><div class="po-chart-hd"><i class="fas fa-tags"></i> Status Distribution</div><div class="po-chart-bd"><canvas id="chStatus"></canvas></div></div>
        <div class="po-chart-card"><div class="po-chart-hd"><i class="fas fa-cubes"></i> Top Items by Value</div><div class="po-chart-bd"><canvas id="chItems"></canvas></div></div>
    </div>
    <div class="po-recent" id="recentTable"></div>
</div>

<?php
/* ── GET/POST Parameters ── */
if (isset($_GET['SelectedStockItem'])) {
    $SelectedStockItem = trim($_GET['SelectedStockItem']);
} elseif (isset($_POST['SelectedStockItem'])) {
    $SelectedStockItem = trim($_POST['SelectedStockItem']);
}

if (isset($_GET['OrderNumber'])) {
    $OrderNumber = $_GET['OrderNumber'];
} elseif (isset($_POST['OrderNumber'])) {
    $OrderNumber = $_POST['OrderNumber'];
}

if (isset($_GET['SelectedSupplier'])) {
    $SelectedSupplier = trim($_GET['SelectedSupplier']);
} elseif (isset($_POST['SelectedSupplier'])) {
    $SelectedSupplier = trim($_POST['SelectedSupplier']);
}

echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '" method="post">
    <div>
    <input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';

if (isset($_POST['ResetPart'])) {
    unset($SelectedStockItem);
}

if (isset($OrderNumber) AND $OrderNumber != '') {
    if (!is_numeric($OrderNumber)) {
        echo '<div style="background:#FFF1F0;border-left:4px solid #FF4D4F;padding:12px 16px;border-radius:8px;margin:12px 0;font-size:13px;">
            <i class="fas fa-exclamation-circle" style="color:#FF4D4F;margin-right:8px;"></i>
            <b>' . _('The Order Number entered') . ' <u>' . _('MUST') . '</u> ' . _('be numeric') . '.</b></div>';
        unset($OrderNumber);
    } else {
        echo '<div style="background:#E6F7F8;border-left:4px solid #2AABB3;padding:12px 16px;border-radius:8px;margin:12px 0;font-size:13px;">
            <i class="fas fa-search" style="color:#2AABB3;margin-right:8px;"></i>' . _('Order Number') . ' - <b>' . $OrderNumber . '</b></div>';
    }
} else {
    if (isset($SelectedSupplier)) {
        echo '<div style="background:#E6F7F8;border-left:4px solid #2AABB3;padding:12px 16px;border-radius:8px;margin:12px 0;font-size:13px;">
            <i class="fas fa-truck" style="color:#2AABB3;margin-right:8px;"></i>' . _('For supplier') . ': <b>' . $SelectedSupplier . '</b></div>';
        echo '<input type="hidden" name="SelectedSupplier" value="' . $SelectedSupplier . '" />';
    }
    if (isset($SelectedStockItem)) {
        echo '<input type="hidden" name="SelectedStockItem" value="' . $SelectedStockItem . '" />';
    }
}

/* ── Stock Part Search ── */
if (isset($_POST['SearchParts'])) {
    if (isset($_POST['Keywords']) AND isset($_POST['StockCode'])) {
        echo '<div style="background:#FFF4E6;border-left:4px solid #FAAD14;padding:10px 16px;border-radius:8px;margin:8px 0;font-size:13px;">
            <i class="fas fa-info-circle" style="color:#FAAD14;margin-right:8px;"></i>' . _('Stock description keywords have been used in preference to the Stock code extract entered') . '</div>';
    }
    if (isset($_POST['StockCat']) AND $_POST['StockCat'] == 'All'){
        $WhereStockCat = ' ';
    } else {
        $WhereStockCat = " AND stockmaster.categoryid='" . $_POST['StockCat'] . "'";
    }
    if ($_POST['Keywords']) {
        $SearchString = '%' . str_replace(' ', '%', $_POST['Keywords']) . '%';
        $SQL = "SELECT stockmaster.stockid, stockmaster.description, SUM(locstock.quantity) AS qoh, stockmaster.units,
                    SUM(purchorderdetails.quantityord-purchorderdetails.quantityrecd) AS qord
                FROM stockmaster INNER JOIN locstock ON stockmaster.stockid = locstock.stockid
                INNER JOIN purchorderdetails ON stockmaster.stockid=purchorderdetails.itemcode
                INNER JOIN purchorders on purchorders.orderno=purchorderdetails.orderno
                INNER JOIN locationusers ON locationusers.loccode=purchorders.intostocklocation AND locationusers.userid='" .  $_SESSION['UserID'] . "' AND locationusers.canview=1
                WHERE purchorderdetails.completed=0
                AND stockmaster.description " . LIKE . " '" . $SearchString . "'
                " . $WhereStockCat . "
                GROUP BY stockmaster.stockid, stockmaster.description, stockmaster.units
                ORDER BY stockmaster.stockid";
    } elseif ($_POST['StockCode']) {
        $SQL = "SELECT stockmaster.stockid, stockmaster.description, SUM(locstock.quantity) AS qoh,
                    SUM(purchorderdetails.quantityord-purchorderdetails.quantityrecd) AS qord, stockmaster.units
                FROM stockmaster INNER JOIN locstock ON stockmaster.stockid = locstock.stockid
                INNER JOIN purchorderdetails ON stockmaster.stockid=purchorderdetails.itemcode
                INNER JOIN purchorders on purchorders.orderno=purchorderdetails.orderno
                INNER JOIN locationusers ON locationusers.loccode=purchorders.intostocklocation AND locationusers.userid='" .  $_SESSION['UserID'] . "' AND locationusers.canview=1
                WHERE purchorderdetails.completed=0
                AND stockmaster.stockid " . LIKE . " '%" . $_POST['StockCode'] . "%'
                " . $WhereStockCat . "
                GROUP BY stockmaster.stockid, stockmaster.description, stockmaster.units
                ORDER BY stockmaster.stockid";
    } else {
        $SQL = "SELECT stockmaster.stockid, stockmaster.description, SUM(locstock.quantity) AS qoh, stockmaster.units,
                    SUM(purchorderdetails.quantityord-purchorderdetails.quantityrecd) AS qord
                FROM stockmaster INNER JOIN locstock ON stockmaster.stockid = locstock.stockid
                INNER JOIN purchorderdetails ON stockmaster.stockid=purchorderdetails.itemcode
                INNER JOIN purchorders on purchorders.orderno=purchorderdetails.orderno
                INNER JOIN locationusers ON locationusers.loccode=purchorders.intostocklocation AND locationusers.userid='" .  $_SESSION['UserID'] . "' AND locationusers.canview=1
                WHERE purchorderdetails.completed=0
                " . $WhereStockCat . "
                GROUP BY stockmaster.stockid, stockmaster.description, stockmaster.units
                ORDER BY stockmaster.stockid";
    }
    $ErrMsg = _('No stock items were returned by the SQL because');
    $DbgMsg = _('The SQL used to retrieve the searched parts was');
    $StockItemsResult = DB_query($SQL, $ErrMsg, $DbgMsg);
}

/* ── Search Forms ── */
if (!isset($OrderNumber) or $OrderNumber == '') {
    if (isset($SelectedSupplier)) {
        echo '<a class="po-add-btn" href="' . $RootPath . '/PO_Header.php?NewOrder=Yes&amp;SupplierID=' . $SelectedSupplier . '"><i class="fas fa-plus"></i> ' . _('Add Purchase Order') . '</a>';
    } else {
        echo '<a class="po-add-btn" href="' . $RootPath . '/PO_Header.php?NewOrder=Yes"><i class="fas fa-plus"></i> ' . _('Add Purchase Order') . '</a>';
    }

    echo '<table class="selection">
            <tr>
                <td>' . _('Order Number') . ': <input type="text" name="OrderNumber" autofocus="autofocus" maxlength="8" size="9" /> &nbsp; ' . _('Into Stock Location') . ':
                <select name="StockLocation">';

    if (!isset($_POST['DateFrom'])) {
        $DateSQL = "SELECT min(orddate) as fromdate, max(orddate) as todate FROM purchorders";
        $DateResult = DB_query($DateSQL);
        $DateRow = DB_fetch_array($DateResult);
        $DateFrom = $DateRow['fromdate'];
        $DateTo = $DateRow['todate'];
    } else {
        $DateFrom = FormatDateForSQL($_POST['DateFrom']);
        $DateTo = FormatDateForSQL($_POST['DateTo']);
    }

    $sql = "SELECT locations.loccode, locationname, (SELECT count(*) FROM locations) AS total FROM locations
                INNER JOIN locationusers ON locationusers.loccode=locations.loccode AND locationusers.userid='" .  $_SESSION['UserID'] . "' AND locationusers.canview=1";
    $ErrMsg = _('Failed to retrieve location data');
    $resultStkLocs = DB_query($sql, $ErrMsg);
    $UserLocations = DB_num_rows($resultStkLocs);
    $AllListed = false;
    while ($myrow = DB_fetch_array($resultStkLocs)) {
        if(!isset($LocQty)){
            $LocQty = $myrow['total'];
        }
        if (isset($_POST['StockLocation'])) {
            if ($_POST['StockLocation'] == 'ALLLOC'){
                if($AllListed === false) {
                    echo '<option selected="selected" value="ALLLOC">' . _('All') . '</option>';
                    echo '<option value="' . $myrow['loccode'] . '">' . $myrow['locationname'] . '</option>';
                    $AllListed = true;
                } else {
                    echo '<option value="' . $myrow['loccode'] . '">' . $myrow['locationname'] . '</option>';
                }
            } else {
                if ($myrow['total'] == $UserLocations) {
                    if($AllListed === false) {
                        echo '<option value="ALLLOC">' . _('All') . '</option>';
                        $AllListed = true;
                    }
                }
                if ($myrow['loccode'] == $_POST['StockLocation']){
                    echo '<option selected="selected" value="' . $myrow['loccode'] . '">' . $myrow['locationname'] . '</option>';
                } else {
                    echo '<option value="' . $myrow['loccode'] . '">' . $myrow['locationname'] . '</option>';
                }
            }
        } else {
            if($myrow['total'] == $UserLocations){
                if($AllListed === false) {
                    echo '<option selected="selected" value="ALLLOC">' . _('All') . '</option>';
                    echo '<option value="' . $myrow['loccode'] . '">' . $myrow['locationname'] . '</option>';
                    $AllListed = true;
                } else {
                    echo '<option value="' . $myrow['loccode'] . '" >' . $myrow['locationname'] . '</option>';
                }
            } else {
                if ($myrow['loccode'] == $_SESSION['UserStockLocation']) {
                    echo '<option selected="selected" value="' . $myrow['loccode'] . '">' . $myrow['locationname'] . '</option>';
                } else {
                    echo '<option value="' . $myrow['loccode'] . '">' . $myrow['locationname'] . '</option>';
                }
            }
        }
    }

    echo '</select> ' . _('Order Status:') . ' <select name="Status">';
    if (!isset($_POST['Status']) OR $_POST['Status'] == 'Pending_Authorised') {
        echo '<option selected="selected" value="Pending_Authorised">' . _('Pending and Authorised') . '</option>';
    } else {
        echo '<option value="Pending_Authorised">' . _('Pending and Authorised') . '</option>';
    }
    if(isset($_POST['Status'])){
        $statusOptions = array('Pending','Authorised','Cancelled','Rejected','DepartmentalAuthorised');
        foreach($statusOptions as $so) {
            $sel = ($_POST['Status'] == $so) ? ' selected="selected"' : '';
            echo '<option' . $sel . ' value="' . $so . '">' . _($so) . '</option>';
        }
    }
    echo '</select>
        ' . _('Orders Between') . ':&nbsp;
            <input type="text" name="DateFrom" value="' . ConvertSQLDate($DateFrom) . '" class="date" size="10" alt="' . $_SESSION['DefaultDateFormat'] . '" />
        ' . _('and') . ':&nbsp;
            <input type="text" name="DateTo" value="' . ConvertSQLDate($DateTo) . '" class="date" size="10" alt="' . $_SESSION['DefaultDateFormat'] . '" />
        <input type="submit" name="SearchOrders" value="' . _('Search Purchase Orders') . '" />
        </td>
        </tr>
        </table>';
}

/* Stock Category search */
$SQL = "SELECT categoryid, categorydescription FROM stockcategory ORDER BY categorydescription";
$result1 = DB_query($SQL);

echo '<div style="background:#FFF4E6;border-left:4px solid #FAAD14;padding:10px 16px;border-radius:8px;margin:12px 0;font-size:13px;">
    <i class="fas fa-info-circle" style="color:#FAAD14;margin-right:8px;"></i>' . _('To search for purchase orders for a specific part use the part selection facilities below') . '</div>';
echo '<table class="selection">
        <tr>';
echo '<td>' . _('Select a stock category') . ':
        <select name="StockCat">';
if (DB_num_rows($result1)>0){
    echo '<option value="All">' . _('All') . '</option>';
}
while ($myrow1 = DB_fetch_array($result1)) {
    if (isset($_POST['StockCat']) and $myrow1['categoryid'] == $_POST['StockCat']) {
        echo '<option selected="selected" value="' . $myrow1['categoryid'] . '">' . $myrow1['categorydescription'] . '</option>';
    } else {
        echo '<option value="' . $myrow1['categoryid'] . '">' . $myrow1['categorydescription'] . '</option>';
    }
}
echo '</select></td>';
echo '<td>' . _('Enter text extracts in the') .' '. '<b>' . _('description') . '</b>:</td>';
echo '<td><input type="text" name="Keywords" size="20" maxlength="25" /></td>
        </tr>
        <tr><td></td>';
echo '<td><b>' . _('OR').' '. '</b>' . _('Enter extract of the') .' '. '<b>' . _('Stock Code') . '</b>:</td>';
echo '<td><input type="text" name="StockCode" size="15" maxlength="18" /></td>
    </tr>
    </table>';
echo '<div style="margin: 12px 0;">
        <input type="submit" name="SearchParts" value="' . _('Search Parts Now') . '" />
        &nbsp;<input type="submit" name="ResetPart" value="' . _('Show All') . '" />
      </div>';

/* ── Stock Search Results ── */
if (isset($StockItemsResult)) {
    echo '<div class="po-results-card">
        <div class="po-results-head">
            <div class="po-results-head-left"><i class="fas fa-cubes"></i> Stock Search Results</div>
        </div>
        <table class="po-table">
        <thead>
        <tr>
            <th>' . _('Code') . '</th>
            <th>' . _('Description') . '</th>
            <th>' . _('On Hand') . '</th>
            <th>' . _('Orders Outstanding') . '</th>
            <th>' . _('Units') . '</th>
        </tr>
        </thead><tbody>';
    while ($myrow = DB_fetch_array($StockItemsResult)) {
        echo '<tr>';
        printf('<td><input type="submit" name="SelectedStockItem" value="%s" style="background:#E6F7F8;color:#1E8F96;border:1px solid #2AABB3;border-radius:6px;padding:4px 10px;font-weight:600;cursor:pointer;font-size:12px;" /></td>
                <td>%s</td>
                <td class="number">%s</td>
                <td class="number">%s</td>
                <td>%s</td></tr>',
                $myrow['stockid'],
                $myrow['description'],
                $myrow['qoh'],
                $myrow['qord'],
                $myrow['units']);
    }
    echo '</tbody></table></div>';
} else {
    /* ── Build PO Listing SQL ── */
    if (!isset($_POST['Status']) OR $_POST['Status'] == 'Pending_Authorised') {
        $StatusCriteria = " AND (purchorders.status='Pending' OR purchorders.status='DepartmentalAuthorised' OR purchorders.status='Authorised' OR purchorders.status='Printed') ";
    } elseif ($_POST['Status'] == 'DepartmentalAuthorised') {
        $StatusCriteria = " AND (purchorders.status='DepartmentalAuthorised' OR purchorders.status='Printed')";
    } elseif ($_POST['Status'] == 'Authorised') {
        $StatusCriteria = " AND (purchorders.status='Authorised' OR purchorders.status='Printed')";
    } elseif ($_POST['Status'] == 'Pending') {
        $StatusCriteria = " AND purchorders.status='Pending' ";
    } elseif ($_POST['Status'] == 'Rejected') {
        $StatusCriteria = " AND purchorders.status='Rejected' ";
    } elseif ($_POST['Status'] == 'Cancelled') {
        $StatusCriteria = " AND purchorders.status='Cancelled' ";
    }

    $selectCols = "purchorders.orderno, purchorders.realorderno, suppliers.suppname, purchorders.orddate, purchorders.deliverydate,
                   purchorders.initiator, purchorders.status, purchorders.requisitionno, purchorders.allowprint,
                   department.departmentname, suppliers.currcode, currencies.decimalplaces AS currdecimalplaces,
                   SUM(purchorderdetails.unitprice*purchorderdetails.quantityord) AS ordervalue";
    $baseTables = "FROM purchorders INNER JOIN purchorderdetails ON purchorders.orderno=purchorderdetails.orderno
                   INNER JOIN department ON purchorders.department=department.departmentid
                   INNER JOIN locationusers ON purchorders.intostocklocation=locationusers.loccode AND userid='" . $_SESSION['UserID'] . "' AND canview=1
                   INNER JOIN suppliers ON purchorders.supplierno = suppliers.supplierid
                   INNER JOIN currencies ON suppliers.currcode=currencies.currabrev";
    $groupBy = "GROUP BY purchorders.orderno, purchorders.realorderno, suppliers.suppname, purchorders.orddate, purchorders.deliverydate,
                purchorders.status, purchorders.initiator, purchorders.requisitionno, purchorders.allowprint,
                department.departmentname, suppliers.currcode, currencies.decimalplaces";

    if (isset($OrderNumber) AND $OrderNumber != '') {
        $SQL = "SELECT $selectCols $baseTables
                WHERE purchorderdetails.completed=0
                AND purchorders.orderno='" . $OrderNumber . "'
                $deptWhere
                $groupBy
                ORDER BY purchorders.orderno DESC";
    } else {
        /* Build WHERE clauses */
        if (!isset($_POST['StockLocation'])) {
            if (isset($UserLocations) AND isset($LocQty) AND $UserLocations == $LocQty) {
                $WhereStockLocation = " ";
                $_POST['StockLocation'] = 'ALLLOC';
            } else {
                $_POST['StockLocation'] = $_SESSION['UserStockLocation'];
                $WhereStockLocation = " AND purchorders.intostocklocation ='" . $_POST['StockLocation'] . "' ";
            }
        } else {
            if ($_POST['StockLocation'] == 'ALLLOC'){
                $WhereStockLocation = ' ';
            } else {
                $WhereStockLocation = " AND purchorders.intostocklocation = '" . $_POST['StockLocation'] . "'";
            }
        }

        $stockItemWhere = '';
        if (isset($SelectedStockItem)) {
            $stockItemWhere = " AND purchorderdetails.itemcode='" . $SelectedStockItem . "'";
        }
        $supplierWhere = '';
        if (isset($SelectedSupplier)) {
            $supplierWhere = " AND purchorders.supplierno='" . $SelectedSupplier . "'";
        }
        $dateWhere = '';
        if (isset($DateFrom) && isset($DateTo)) {
            $dateWhere = " AND orddate>='" . $DateFrom . "' AND orddate<='" . $DateTo . "'";
        }

        $SQL = "SELECT $selectCols $baseTables
                WHERE purchorderdetails.completed=0
                $dateWhere $stockItemWhere $supplierWhere $WhereStockLocation $StatusCriteria $deptWhere
                $groupBy
                ORDER BY purchorders.orderno DESC";
    }

    $ErrMsg = _('No orders were returned by the SQL because');
    $PurchOrdersResult = DB_query($SQL, $ErrMsg);

    /* ── Pagination Logic ── */
    $allRows = array();
    while ($row = DB_fetch_array($PurchOrdersResult)) {
        $allRows[] = $row;
    }
    $totalRows = count($allRows);
    $perPage = 25;
    $totalPages = max(1, ceil($totalRows / $perPage));
    $currentPage = isset($_GET['pg']) ? max(1, min((int)$_GET['pg'], $totalPages)) : 1;
    $offset = ($currentPage - 1) * $perPage;
    $pageRows = array_slice($allRows, $offset, $perPage);

    /* ── Render PO Table ── */
    echo '<div class="po-results-card">';
    echo '<div class="po-results-head">
            <div class="po-results-head-left"><i class="fas fa-file-invoice"></i> Purchase Order Results</div>
            <span class="po-results-count">' . number_format($totalRows) . ' orders found &middot; Page ' . $currentPage . ' of ' . $totalPages . '</span>
          </div>';

    echo '<table class="po-table">
        <thead>
        <tr>
            <th>' . _('Order #') . '</th>
            <th>' . _('Order Date') . '</th>
            <th>' . _('Delivery Date') . '</th>
            <th>' . _('Department') . '</th>
            <th>' . _('Initiated By') . '</th>
            <th>' . _('Supplier') . '</th>
            <th>' . _('Currency') . '</th>';
    if (in_array($PricesSecurity, $_SESSION['AllowedPageSecurityTokens']) OR !isset($PricesSecurity)) {
        echo '<th>' . _('Order Total') . '</th>';
    }
    echo '  <th>' . _('Status') . '</th>
            <th>' . _('Print') . '</th>
            <th>' . _('Receive') . '</th>
        </tr>
        </thead><tbody>';

    if ($totalRows == 0) {
        echo '<tr><td colspan="11" style="text-align:center;padding:40px;color:#9CA3AF;">
            <i class="fas fa-inbox" style="font-size:36px;margin-bottom:12px;display:block;color:#D1D5DB;"></i>
            No purchase orders found matching your criteria</td></tr>';
    }

    foreach ($pageRows as $myrow) {
        $ModifyPage = $RootPath . '/PO_Header.php?ModifyOrderNumber=' . $myrow['orderno'];

        /* Receive link */
        $ReceiveOrder = '';
        if ($myrow['status'] == 'Printed') {
            $ReceiveOrder = '<a class="po-action po-action-receive" href="' . $RootPath . '/GoodsReceived.php?PONumber=' . $myrow['orderno'] . '"><i class="fas fa-truck-loading"></i> ' . _('Receive') . '</a>';
        }

        /* Print link */
        if ($myrow['status'] == 'Authorised' AND $myrow['allowprint'] == 1) {
            $PrintPurchOrder = '<a class="po-action po-action-print" href="' . $RootPath . '/PO_PDFPurchOrder.php?OrderNo=' . $myrow['orderno'] . '"><i class="fas fa-print"></i> ' . _('Print') . '</a>';
        } elseif ($myrow['status'] == 'Authorised' AND $myrow['allowprint'] == 0) {
            $PrintPurchOrder = '<span style="color:#9CA3AF;font-size:11px;">' . _('Printed') . '</span>';
        } elseif ($myrow['status'] == 'Printed') {
            $PrintPurchOrder = '<a class="po-action po-action-print" href="' . $RootPath . '/PO_PDFPurchOrder.php?OrderNo=' . $myrow['orderno'] . '&amp;realorderno=' . $myrow['realorderno'] . '&amp;ViewingOnly=2"><i class="fas fa-copy"></i> ' . _('Print Copy') . '</a>';
        } else {
            $PrintPurchOrder = '<span style="color:#D1D5DB;font-size:11px;">N/A</span>';
        }

        $FormatedOrderDate = ConvertSQLDate($myrow['orddate']);
        $FormatedDeliveryDate = ConvertSQLDate($myrow['deliverydate']);
        $department = $myrow['departmentname'];
        $FormatedOrderValue = locale_number_format($myrow['ordervalue'], $myrow['currdecimalplaces']);

        /* Initiator name lookup */
        $sqlUser = "SELECT realname FROM www_users WHERE userid='" . $myrow['initiator'] . "'";
        $UserResult = DB_query($sqlUser);
        $MyUserRow = DB_fetch_array($UserResult);
        $InitiatorName = isset($MyUserRow['realname']) ? $MyUserRow['realname'] : $myrow['initiator'];

        /* Status badge class */
        $statusLower = strtolower(str_replace(' ', '', $myrow['status']));
        $statusClass = 'po-status-' . $statusLower;

        echo '<tr>
            <td><a class="po-order-link" href="' . $ModifyPage . '">' . $myrow['orderno'] . '</a></td>
            <td>' . $FormatedOrderDate . '</td>
            <td>' . $FormatedDeliveryDate . '</td>
            <td>' . $department . '</td>
            <td>' . $InitiatorName . '</td>
            <td>' . $myrow['suppname'] . '</td>
            <td>' . $myrow['currcode'] . '</td>';
        if (in_array($PricesSecurity, $_SESSION['AllowedPageSecurityTokens']) OR !isset($PricesSecurity)) {
            echo '<td style="text-align:right;font-weight:600;">' . $FormatedOrderValue . '</td>';
        }
        echo '<td><span class="po-status ' . $statusClass . '">' . _($myrow['status']) . '</span></td>
            <td>' . $PrintPurchOrder . '</td>
            <td>' . $ReceiveOrder . '</td>
            </tr>';
    }

    echo '</tbody></table>';

    /* ── Pagination Controls ── */
    if ($totalPages > 1) {
        /* Build base URL preserving POST params as GET for pagination */
        $baseUrl = htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8');

        echo '<div class="po-pagination">';

        /* Prev */
        if ($currentPage > 1) {
            echo '<a href="' . $baseUrl . '?pg=' . ($currentPage - 1) . '" title="Previous"><i class="fas fa-chevron-left"></i></a>';
        } else {
            echo '<span class="disabled"><i class="fas fa-chevron-left"></i></span>';
        }

        /* Page numbers */
        $startPage = max(1, $currentPage - 3);
        $endPage = min($totalPages, $currentPage + 3);

        if ($startPage > 1) {
            echo '<a href="' . $baseUrl . '?pg=1">1</a>';
            if ($startPage > 2) echo '<span class="page-info">...</span>';
        }

        for ($p = $startPage; $p <= $endPage; $p++) {
            if ($p == $currentPage) {
                echo '<span class="current">' . $p . '</span>';
            } else {
                echo '<a href="' . $baseUrl . '?pg=' . $p . '">' . $p . '</a>';
            }
        }

        if ($endPage < $totalPages) {
            if ($endPage < $totalPages - 1) echo '<span class="page-info">...</span>';
            echo '<a href="' . $baseUrl . '?pg=' . $totalPages . '">' . $totalPages . '</a>';
        }

        /* Next */
        if ($currentPage < $totalPages) {
            echo '<a href="' . $baseUrl . '?pg=' . ($currentPage + 1) . '" title="Next"><i class="fas fa-chevron-right"></i></a>';
        } else {
            echo '<span class="disabled"><i class="fas fa-chevron-right"></i></span>';
        }

        echo '<span class="page-info">(' . number_format($totalRows) . ' total)</span>';
        echo '</div>';
    }

    echo '</div>'; /* end po-results-card */
}

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


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

</div><!-- end po-wrap -->

<script>
var MN=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var PAL=['#2AABB3','#1890FF','#52C41A','#FAAD14','#FF4D4F','#722ED1','#13C2C2','#FA541C'];
var STCOL={'Pending':'#FAAD14','Authorised':'#52C41A','Printed':'#1890FF','Cancelled':'#FF4D4F','Rejected':'#FF7A45','DepartmentalAuthorised':'#722ED1'};
function fmt(n){return '$'+Number(n).toLocaleString('en-US',{minimumFractionDigits:0,maximumFractionDigits:0})}
function fK(n){return n>=1e6?'$'+(n/1e6).toFixed(1)+'M':n>=1e3?'$'+(n/1e3).toFixed(0)+'K':'$'+Math.round(n)}
function pct(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 kpi(icon,ic,val,label,sub,bc,delta){var dH='';if(delta){var c=delta.dir==='up'?'kd-up':delta.dir==='down'?'kd-down':'kd-flat';var a=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>':'';dH='<div class="kd '+c+'">'+a+' '+delta.val+'% vs PY</div>';}var sH=sub?'<div class="ks">'+sub+'</div>':'';return '<div class="po-kpi" style="border-left-color:'+bc+'"><div class="po-kpi-top"><div class="po-kpi-icon '+ic+'"><i class="fas '+icon+'"></i></div></div><div class="kv">'+val+'</div><div class="kl">'+label+'</div>'+sH+dH+'</div>';}
function co(t,o){var b={responsive:true,maintainAspectRatio:false,animation:false,plugins:{legend:{display:false}}};for(var k in o)b[k]=o[k];return b;}
function render(d){
document.getElementById('bOS').textContent=d.os_total.toLocaleString();document.getElementById('bOSVal').textContent=fK(d.os_val);document.getElementById('bYTD').textContent=d.total_cy.toLocaleString();document.getElementById('bYTDVal').textContent=fK(d.ytd_val_cy);document.getElementById('bSupp').textContent=d.unique_suppliers.toLocaleString();document.getElementById('yearLabel').textContent=d.cur_year;
var pT=pct(d.total_cy,d.total_py),pV=pct(d.ytd_val_cy,d.ytd_val_py);
document.getElementById('kpiYear').innerHTML=kpi('fa-file-invoice-dollar','ic-teal',d.total_cy.toLocaleString(),d.cur_year+' Total POs',null,'#2AABB3',pT)+kpi('fa-dollar-sign','ic-green',fK(d.ytd_val_cy),d.cur_year+' YTD Value',null,'#52C41A',pV)+kpi('fa-calendar-day','ic-blue',d.month_cnt.toLocaleString(),'This Month Orders',d.cur_month_name,'#1890FF')+kpi('fa-chart-bar','ic-purple',fK(d.avg_po_val),'Average PO Value','Per order','#722ED1');
var cyV=new Array(12).fill(0),pyV=new Array(12).fill(0);d.monthly_trend.forEach(function(r){cyV[parseInt(r.m)-1]=parseFloat(r.val)});d.monthly_trend_py.forEach(function(r){pyV[parseInt(r.m)-1]=parseFloat(r.val)});
new Chart(document.getElementById('chTrend'),{type:'line',data:{labels:MN,datasets:[{label:d.cur_year+' Value',data:cyV,borderColor:'#2AABB3',backgroundColor:'rgba(42,171,179,0.1)',fill:true,tension:.4,borderWidth:2,pointRadius:3,pointBackgroundColor:'#2AABB3'},{label:d.prev_year+' Value',data:pyV,borderColor:'#D1D5DB',backgroundColor:'transparent',borderDash:[5,3],tension:.4,borderWidth:1.5,pointRadius:2,pointBackgroundColor:'#D1D5DB'}]},options:co('l',{plugins:{legend:{display:true,position:'top',labels:{font:{size:10,family:'Poppins'},boxWidth:12,padding:8}}},scales:{y:{ticks:{callback:function(v){return fK(v)},font:{size:10,family:'Poppins'}},grid:{color:'#F0F0F0'}},x:{ticks:{font:{size:10,family:'Poppins'}},grid:{display:false}}}})});
var cyC=new Array(12).fill(0),pyC=new Array(12).fill(0);d.monthly_trend.forEach(function(r){cyC[parseInt(r.m)-1]=parseInt(r.cnt)});d.monthly_trend_py.forEach(function(r){pyC[parseInt(r.m)-1]=parseInt(r.cnt)});
new Chart(document.getElementById('chCount'),{type:'bar',data:{labels:MN,datasets:[{label:d.cur_year,data:cyC,backgroundColor:'rgba(42,171,179,0.7)',borderRadius:4,maxBarThickness:18},{label:d.prev_year,data:pyC,backgroundColor:'rgba(209,213,219,0.5)',borderRadius:4,maxBarThickness:18}]},options:co('b',{plugins:{legend:{display:true,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}}}})});
var sL=[],sV=[];d.top_suppliers.forEach(function(r){sL.push(r.suppname.substring(0,25));sV.push(parseFloat(r.val))});
new Chart(document.getElementById('chSupp'),{type:'bar',data:{labels:sL,datasets:[{data:sV,backgroundColor:PAL.slice(0,sV.length),borderRadius:4,maxBarThickness:16}]},options:co('b',{indexAxis:'y',scales:{x:{ticks:{callback:function(v){return fK(v)},font:{size:10,family:'Poppins'}},grid:{color:'#F0F0F0'}},y:{ticks:{font:{size:10,family:'Poppins'}},grid:{display:false}}}})});
var dL=[],dV=[];d.dept_breakdown.forEach(function(r){dL.push(r.departmentname.substring(0,20));dV.push(parseFloat(r.val))});
new Chart(document.getElementById('chDept'),{type:'doughnut',data:{labels:dL,datasets:[{data:dV,backgroundColor:PAL.slice(0,dV.length),borderWidth:1,hoverOffset:6}]},options:co('d',{cutout:'60%',plugins:{legend:{display:true,position:'right',labels:{font:{size:10,family:'Poppins'},boxWidth:10,padding:6}}}})});
var stL=[],stV=[],stC=[];d.status_dist.forEach(function(r){stL.push(r.status);stV.push(parseInt(r.cnt));stC.push(STCOL[r.status]||'#D1D5DB')});
new Chart(document.getElementById('chStatus'),{type:'doughnut',data:{labels:stL,datasets:[{data:stV,backgroundColor:stC,borderWidth:1,hoverOffset:6}]},options:co('d',{cutout:'60%',plugins:{legend:{display:true,position:'right',labels:{font:{size:10,family:'Poppins'},boxWidth:10,padding:6}}}})});
var iL=[],iV=[];d.top_items.forEach(function(r){iL.push(r.itemdescription.substring(0,30));iV.push(parseFloat(r.val))});
new Chart(document.getElementById('chItems'),{type:'bar',data:{labels:iL,datasets:[{data:iV,backgroundColor:'rgba(42,171,179,0.65)',borderRadius:4,maxBarThickness:14}]},options:co('b',{indexAxis:'y',scales:{x:{ticks:{callback:function(v){return fK(v)},font:{size:9,family:'Poppins'}},grid:{color:'#F0F0F0'}},y:{ticks:{font:{size:9,family:'Poppins'}},grid:{display:false}}}})});
var h='<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>';
h+='<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,'');h+='<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 sb-'+sc+'">'+r.status+'</span></td></tr>';});
h+='</tbody></table>';document.getElementById('recentTable').innerHTML=h;
}
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 st=Date.now(),el=document.getElementById('poLoadTimer');
var ti=setInterval(function(){if(el)el.textContent='Loading data... '+((Date.now()-st)/1000).toFixed(1)+'s'},100);
var x=new XMLHttpRequest();
x.open('GET','PO_SelectOSPurchOrder.php?api=dashboard',true);
x.onreadystatechange=function(){if(x.readyState===4){clearInterval(ti);var m=document.getElementById('poLoadingModal');if(m){m.style.opacity='0';m.style.transition='opacity 0.3s';setTimeout(function(){m.style.display='none'},300)}if(x.status===200){try{render(JSON.parse(x.responseText))}catch(e){console.error('Dashboard parse error',e)}}}};
x.send();
})();
</script>

<?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'];
}
?>