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

include('includes/session.inc');
$Title=_('Overseas Purchase Orders');
include('includes/newheader.php');
include('includes/SQL_CommonFunctions.inc');

$userid = $_SESSION['UserID'];

/* ── Loading Modal (render immediately, flush to browser) ── */
?>
<style>
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');

/* ── Loading Modal ── */
.opo-loading-overlay{position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(255,255,255,.92);z-index:99999;display:flex;align-items:center;justify-content:center;flex-direction:column;transition:opacity .5s}
.opo-loading-overlay.fade-out{opacity:0;pointer-events:none}
.opo-spinner{width:48px;height:48px;border:4px solid #E6F7F8;border-top-color:#2AABB3;border-radius:50%;animation:opoSpin .8s linear infinite}
@keyframes opoSpin{to{transform:rotate(360deg)}}
.opo-loading-text{margin-top:16px;font-family:'Poppins',sans-serif;color:#1E8F96;font-size:14px;font-weight:500}

/* ── CSS Variables ── */
:root{
  --opo-primary:#2AABB3;--opo-dark:#1E8F96;--opo-darker:#187278;
  --opo-light:#E6F7F8;--opo-lighter:#F0FBFC;
  --opo-success:#52C41A;--opo-warning:#FAAD14;--opo-danger:#FF4D4F;--opo-blue:#1890FF;--opo-purple:#722ED1;
  --opo-text:#1F2937;--opo-muted:#6B7280;--opo-border:#E5E7EB;
  --opo-radius:10px;--opo-shadow:0 1px 3px rgba(0,0,0,.06),0 1px 2px rgba(0,0,0,.04);
  --opo-shadow-md:0 4px 12px rgba(42,171,179,.10);
}

/* ── Page Header Banner ── */
.opo-banner{background:linear-gradient(135deg,#187278 0%,#1E8F96 40%,#2AABB3 100%);border-radius:var(--opo-radius);padding:28px 32px 22px;margin:0 0 24px;position:relative;overflow:hidden;font-family:'Poppins',sans-serif}
.opo-banner::before{content:'';position:absolute;top:-60px;right:-40px;width:200px;height:200px;background:rgba(255,255,255,.06);border-radius:50%}
.opo-banner::after{content:'';position:absolute;bottom:-80px;right:120px;width:160px;height:160px;background:rgba(255,255,255,.04);border-radius:50%}
.opo-banner-content{position:relative;z-index:1}
.opo-breadcrumb{display:flex;align-items:center;gap:8px;margin-bottom:10px;font-size:12px;color:rgba(255,255,255,.7)}
.opo-breadcrumb a{color:rgba(255,255,255,.7);text-decoration:none}
.opo-breadcrumb a:hover{color:#fff}
.opo-breadcrumb .sep{margin:0 2px}
.opo-banner-row{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:16px}
.opo-banner h1{color:#fff;font-size:22px;font-weight:700;margin:0;letter-spacing:-.3px}
.opo-banner h1 i{margin-right:10px;opacity:.9}
.opo-banner-stats{display:flex;gap:20px;flex-wrap:wrap}
.opo-banner-stat{text-align:center;padding:6px 16px;background:rgba(255,255,255,.12);border-radius:8px;min-width:80px;backdrop-filter:blur(4px)}
.opo-banner-stat .num{font-size:20px;font-weight:700;color:#fff;line-height:1.2}
.opo-banner-stat .lbl{font-size:10px;color:rgba(255,255,255,.75);text-transform:uppercase;letter-spacing:.5px;margin-top:2px}

/* ── Dashboard Toggle ── */
.opo-dash-toggle{display:flex;align-items:center;gap:8px;margin-bottom:18px;cursor:pointer;font-family:'Poppins',sans-serif;font-size:13px;color:var(--opo-muted);user-select:none;padding:0}
.opo-dash-toggle:hover{color:var(--opo-dark)}
.opo-dash-toggle i{font-size:10px;transition:transform .25s}
.opo-dash-toggle.collapsed i{transform:rotate(-90deg)}
.opo-dashboard{transition:max-height .4s ease,opacity .3s;overflow:hidden;max-height:2000px;opacity:1}
.opo-dashboard.collapsed{max-height:0;opacity:0}

/* ── KPI Cards ── */
.opo-kpi-grid{display:grid;grid-template-columns:repeat(5,1fr);gap:16px;margin-bottom:24px}
@media(max-width:1200px){.opo-kpi-grid{grid-template-columns:repeat(3,1fr)}}
@media(max-width:768px){.opo-kpi-grid{grid-template-columns:repeat(2,1fr)}}
.opo-kpi{background:#fff;border-radius:var(--opo-radius);padding:20px;border:1px solid var(--opo-border);box-shadow:var(--opo-shadow);transition:all .2s;position:relative;overflow:hidden}
.opo-kpi:hover{box-shadow:var(--opo-shadow-md);transform:translateY(-2px)}
.opo-kpi-accent{position:absolute;top:0;left:0;right:0;height:3px}
.opo-kpi .top{display:flex;align-items:center;justify-content:space-between;margin-bottom:12px}
.opo-kpi .label{font-size:12px;color:var(--opo-muted);font-weight:500;text-transform:uppercase;letter-spacing:.3px;font-family:'Poppins',sans-serif}
.opo-kpi .icon{width:36px;height:36px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:16px}
.opo-kpi .value{font-size:26px;font-weight:700;color:var(--opo-text);line-height:1.1;font-family:'Poppins',sans-serif}
.opo-kpi .sub{font-size:11px;color:var(--opo-muted);margin-top:6px;font-family:'Poppins',sans-serif}

/* ── Chart Containers ── */
.opo-charts-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin-bottom:24px}
@media(max-width:1100px){.opo-charts-grid{grid-template-columns:repeat(2,1fr)}}
@media(max-width:768px){.opo-charts-grid{grid-template-columns:1fr}}
.opo-chart-card{background:#fff;border-radius:var(--opo-radius);padding:20px;border:1px solid var(--opo-border);box-shadow:var(--opo-shadow)}
.opo-chart-card h3{font-family:'Poppins',sans-serif;font-size:13px;font-weight:600;color:var(--opo-text);margin:0 0 16px;display:flex;align-items:center;gap:8px}
.opo-chart-card h3 i{color:var(--opo-primary)}
.opo-chart-wrap{position:relative;max-height:220px}

/* ── Recent Orders Table ── */
.opo-recent-card{background:#fff;border-radius:var(--opo-radius);padding:20px;border:1px solid var(--opo-border);box-shadow:var(--opo-shadow);margin-bottom:24px}
.opo-recent-card h3{font-family:'Poppins',sans-serif;font-size:13px;font-weight:600;color:var(--opo-text);margin:0 0 16px;display:flex;align-items:center;gap:8px}
.opo-recent-card h3 i{color:var(--opo-primary)}
.opo-tbl{width:100%;border-collapse:separate;border-spacing:0;font-family:'Poppins',sans-serif;font-size:12px}
.opo-tbl thead th{background:linear-gradient(135deg,#1E8F96,#2AABB3);color:#fff;padding:10px 14px;text-align:left;font-weight:500;white-space:nowrap;font-size:11px;text-transform:uppercase;letter-spacing:.3px}
.opo-tbl thead th:first-child{border-radius:8px 0 0 0}
.opo-tbl thead th:last-child{border-radius:0 8px 0 0}
.opo-tbl tbody tr{transition:background .15s}
.opo-tbl tbody tr:hover{background:var(--opo-lighter)}
.opo-tbl tbody td{padding:10px 14px;border-bottom:1px solid var(--opo-border);color:var(--opo-text)}
.opo-badge{display:inline-block;padding:3px 10px;border-radius:12px;font-size:11px;font-weight:600;line-height:1.4}
.opo-badge-draft{background:#FFF7E6;color:#D48806}
.opo-badge-approved{background:#E6F7FF;color:#1890FF}
.opo-badge-printed{background:#F6FFED;color:#52C41A}
.opo-badge-received{background:#F0F0F0;color:#595959}
.opo-pill{display:inline-block;background:var(--opo-light);color:var(--opo-dark);padding:2px 10px;border-radius:12px;font-weight:600;font-size:12px;text-decoration:none}

/* ── Xcrud Overlay ── */
.opo-xcrud-wrap{font-family:'Poppins',sans-serif}
.opo-xcrud-wrap .xcrud-nav{border-radius:8px;overflow:hidden}
.opo-xcrud-wrap .xcrud-top-actions,.opo-xcrud-wrap .xcrud-list{font-family:'Poppins',sans-serif}
.opo-xcrud-wrap .xcrud-row:hover{background:var(--opo-lighter) !important}
.opo-xcrud-wrap th.xcrud-th{background:linear-gradient(135deg,#1E8F96,#2AABB3) !important;color:#fff !important;font-weight:500;text-transform:uppercase;font-size:11px;letter-spacing:.3px;padding:10px 12px !important}
.opo-xcrud-wrap .xcrud-pagination a,.opo-xcrud-wrap .xcrud-pagination span{border-radius:6px !important}
.opo-xcrud-wrap .btn.westpac{background:var(--opo-primary) !important;border-color:var(--opo-dark) !important;color:#fff !important;border-radius:6px !important;font-size:12px !important;font-family:'Poppins',sans-serif !important}
.opo-xcrud-wrap .btn.westpac:hover{background:var(--opo-darker) !important}
</style>

<div class="opo-loading-overlay" id="opoLoadingOverlay">
  <div class="opo-spinner"></div>
  <div class="opo-loading-text">Loading Overseas Purchase Orders...</div>
</div>

<?php
ob_flush();
flush();

/* ── Direct Database Connection ── */
$dbOPO = new mysqli('localhost','sooggoo','4Compassion*','evergreentest');
if($dbOPO->connect_error){ echo '<p style="color:red">DB Error</p>'; }

/* ── Authorized Users ── */
$authorizedUsers = array('admin','mosheed','sharukh','ravneet','sachin','ravinesh');
$isAuthorized = in_array($userid, $authorizedUsers);

if($isAuthorized){

/* ── Dashboard Queries ── */

// Total OPOs
$r = $dbOPO->query("SELECT COUNT(*) as cnt FROM overseas_purchase_orders");
$totalOPOs = ($r) ? $r->fetch_assoc() : array('cnt'=>0);
$totalOPOs = $totalOPOs['cnt'];

// By Status
$r = $dbOPO->query("SELECT status, COUNT(*) as cnt, COALESCE(SUM(d.line_total),0) as val
    FROM overseas_purchase_orders o
    LEFT JOIN (
        SELECT id, SUM(total_price) as line_total FROM overseas_purchase_orders_details GROUP BY id
    ) d ON o.id = d.id
    GROUP BY o.status");
$statusData = array('Draft'=>array('cnt'=>0,'val'=>0),'Approved'=>array('cnt'=>0,'val'=>0),'Printed'=>array('cnt'=>0,'val'=>0),'Received'=>array('cnt'=>0,'val'=>0));
if($r){ while($row=$r->fetch_assoc()){ $statusData[$row['status']] = array('cnt'=>$row['cnt'],'val'=>$row['val']); } }

// Total Value
$r = $dbOPO->query("SELECT COALESCE(SUM(total_price),0) as total FROM overseas_purchase_orders_details");
$totalValue = ($r) ? $r->fetch_assoc() : array('total'=>0);
$totalValue = $totalValue['total'];

// This Year Value
$thisYear = date('Y');
$r = $dbOPO->query("SELECT COALESCE(SUM(d.total_price),0) as val
    FROM overseas_purchase_orders_details d
    JOIN overseas_purchase_orders o ON d.id = o.id
    WHERE YEAR(o.entered_date) = '".$thisYear."'");
$thisYearVal = ($r) ? $r->fetch_assoc() : array('val'=>0);
$thisYearVal = $thisYearVal['val'];

// Last Year Value
$lastYear = $thisYear - 1;
$r = $dbOPO->query("SELECT COALESCE(SUM(d.total_price),0) as val
    FROM overseas_purchase_orders_details d
    JOIN overseas_purchase_orders o ON d.id = o.id
    WHERE YEAR(o.entered_date) = '".$lastYear."'");
$lastYearVal = ($r) ? $r->fetch_assoc() : array('val'=>0);
$lastYearVal = $lastYearVal['val'];

// By Currency
$r = $dbOPO->query("SELECT o.currency, COUNT(*) as cnt, COALESCE(SUM(d.line_total),0) as val
    FROM overseas_purchase_orders o
    LEFT JOIN (SELECT id, SUM(total_price) as line_total FROM overseas_purchase_orders_details GROUP BY id) d ON o.id = d.id
    GROUP BY o.currency ORDER BY val DESC LIMIT 6");
$currencyLabels = array(); $currencyValues = array();
if($r){ while($row=$r->fetch_assoc()){ $currencyLabels[] = $row['currency'] ? $row['currency'] : 'N/A'; $currencyValues[] = round($row['val'],2); } }

// By Shipment Mode
$r = $dbOPO->query("SELECT shipment_mode, COUNT(*) as cnt FROM overseas_purchase_orders WHERE shipment_mode != '' GROUP BY shipment_mode ORDER BY cnt DESC");
$shipLabels = array(); $shipValues = array();
if($r){ while($row=$r->fetch_assoc()){ $shipLabels[] = $row['shipment_mode']; $shipValues[] = intval($row['cnt']); } }

// Top Suppliers
$r = $dbOPO->query("SELECT s.suppname, COUNT(*) as cnt, COALESCE(SUM(d.line_total),0) as val
    FROM overseas_purchase_orders o
    LEFT JOIN suppliers s ON o.supplier_name = s.supplierid
    LEFT JOIN (SELECT id, SUM(total_price) as line_total FROM overseas_purchase_orders_details GROUP BY id) d ON o.id = d.id
    GROUP BY o.supplier_name ORDER BY val DESC LIMIT 6");
$suppLabels = array(); $suppValues = array(); $suppCounts = array();
if($r){ while($row=$r->fetch_assoc()){
    $name = $row['suppname'] ? $row['suppname'] : 'Unknown';
    if(strlen($name)>25) $name = substr($name,0,22).'...';
    $suppLabels[] = $name; $suppValues[] = round($row['val'],2); $suppCounts[] = intval($row['cnt']);
} }

// Monthly Trend (last 12 months)
$r = $dbOPO->query("SELECT DATE_FORMAT(o.entered_date,'%Y-%m') as ym, COUNT(*) as cnt, COALESCE(SUM(d.line_total),0) as val
    FROM overseas_purchase_orders o
    LEFT JOIN (SELECT id, SUM(total_price) as line_total FROM overseas_purchase_orders_details GROUP BY id) d ON o.id = d.id
    WHERE o.entered_date >= DATE_SUB(NOW(), INTERVAL 12 MONTH)
    GROUP BY ym ORDER BY ym ASC");
$trendLabels = array(); $trendCounts = array(); $trendValues = array();
if($r){ while($row=$r->fetch_assoc()){
    $trendLabels[] = date('M Y', strtotime($row['ym'].'-01'));
    $trendCounts[] = intval($row['cnt']);
    $trendValues[] = round($row['val'],2);
} }

// Recent 10 Orders
$r = $dbOPO->query("SELECT o.id, o.status, o.currency, o.shipment_mode, o.entered_by, o.entered_date, o.quote_no,
    s.suppname, COALESCE(d.line_total,0) as total_val, COALESCE(d.items,0) as item_count
    FROM overseas_purchase_orders o
    LEFT JOIN suppliers s ON o.supplier_name = s.supplierid
    LEFT JOIN (SELECT id, SUM(total_price) as line_total, COUNT(*) as items FROM overseas_purchase_orders_details GROUP BY id) d ON o.id = d.id
    ORDER BY o.id DESC LIMIT 10");
$recentOrders = array();
if($r){ while($row=$r->fetch_assoc()){ $recentOrders[] = $row; } }

// By Department
$r = $dbOPO->query("SELECT dp.departmentname, COUNT(*) as cnt
    FROM overseas_purchase_orders o
    LEFT JOIN department dp ON o.department = dp.departmentid
    GROUP BY o.department ORDER BY cnt DESC LIMIT 6");
$deptLabels = array(); $deptValues = array();
if($r){ while($row=$r->fetch_assoc()){
    $name = $row['departmentname'] ? $row['departmentname'] : 'Unassigned';
    if(strlen($name)>20) $name = substr($name,0,17).'...';
    $deptLabels[] = $name; $deptValues[] = intval($row['cnt']);
} }

$dbOPO->close();

/* ── Compute KPI deltas ── */
$yoyChange = ($lastYearVal > 0) ? round((($thisYearVal - $lastYearVal)/$lastYearVal)*100,1) : 0;
$yoyArrow = ($yoyChange >= 0) ? '&#9650;' : '&#9660;';
$yoyColor = ($yoyChange >= 0) ? 'var(--opo-success)' : 'var(--opo-danger)';

?>

<!-- ── Page Wrapper ── -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"/>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>

<div style="padding:0 8px;font-family:'Poppins',sans-serif">

<!-- ── Banner ── -->
<div class="opo-banner">
  <div class="opo-banner-content">
    <div class="opo-breadcrumb">
      <a href="index.php"><i class="fa fa-home"></i> Home</a>
      <span class="sep">›</span>
      <a href="#">Purchasing</a>
      <span class="sep">›</span>
      <span style="color:#fff">Overseas Purchase Orders</span>
    </div>
    <div class="opo-banner-row">
      <h1><i class="fa fa-ship"></i> Overseas Purchase Orders</h1>
      <div class="opo-banner-stats">
        <div class="opo-banner-stat"><div class="num"><?php echo $totalOPOs; ?></div><div class="lbl">Total Orders</div></div>
        <div class="opo-banner-stat"><div class="num"><?php echo $statusData['Draft']['cnt']; ?></div><div class="lbl">Draft</div></div>
        <div class="opo-banner-stat"><div class="num"><?php echo $statusData['Approved']['cnt']; ?></div><div class="lbl">Approved</div></div>
        <div class="opo-banner-stat"><div class="num"><?php echo $statusData['Printed']['cnt']; ?></div><div class="lbl">Printed</div></div>
        <div class="opo-banner-stat"><div class="num"><?php echo $statusData['Received']['cnt']; ?></div><div class="lbl">Received</div></div>
      </div>
    </div>
  </div>
</div>

<!-- ── Dashboard Toggle ── -->
<div class="opo-dash-toggle" id="opoDashToggle" onclick="toggleOpoDash()">
  <i class="fa fa-chevron-down" id="opoDashIcon"></i>
  <span>Dashboard Analytics</span>
</div>

<div class="opo-dashboard" id="opoDashboard">

<!-- ── KPI Cards ── -->
<div class="opo-kpi-grid">
  <div class="opo-kpi">
    <div class="opo-kpi-accent" style="background:var(--opo-primary)"></div>
    <div class="top">
      <div class="label">Total Orders</div>
      <div class="icon" style="background:var(--opo-light);color:var(--opo-dark)"><i class="fa fa-file-lines"></i></div>
    </div>
    <div class="value"><?php echo number_format($totalOPOs); ?></div>
    <div class="sub">All overseas purchase orders</div>
  </div>

  <div class="opo-kpi">
    <div class="opo-kpi-accent" style="background:var(--opo-warning)"></div>
    <div class="top">
      <div class="label">Pending (Draft)</div>
      <div class="icon" style="background:#FFF7E6;color:#D48806"><i class="fa fa-clock"></i></div>
    </div>
    <div class="value"><?php echo number_format($statusData['Draft']['cnt']); ?></div>
    <div class="sub">$<?php echo number_format($statusData['Draft']['val'],2); ?> value</div>
  </div>

  <div class="opo-kpi">
    <div class="opo-kpi-accent" style="background:var(--opo-blue)"></div>
    <div class="top">
      <div class="label">Approved</div>
      <div class="icon" style="background:#E6F7FF;color:#1890FF"><i class="fa fa-check-circle"></i></div>
    </div>
    <div class="value"><?php echo number_format($statusData['Approved']['cnt']); ?></div>
    <div class="sub">$<?php echo number_format($statusData['Approved']['val'],2); ?> value</div>
  </div>

  <div class="opo-kpi">
    <div class="opo-kpi-accent" style="background:var(--opo-success)"></div>
    <div class="top">
      <div class="label"><?php echo $thisYear; ?> Spend</div>
      <div class="icon" style="background:#F6FFED;color:#52C41A"><i class="fa fa-dollar-sign"></i></div>
    </div>
    <div class="value">$<?php echo number_format($thisYearVal,0); ?></div>
    <div class="sub"><span style="color:<?php echo $yoyColor; ?>"><?php echo $yoyArrow; ?> <?php echo abs($yoyChange); ?>%</span> vs <?php echo $lastYear; ?></div>
  </div>

  <div class="opo-kpi">
    <div class="opo-kpi-accent" style="background:var(--opo-purple)"></div>
    <div class="top">
      <div class="label">Total Value</div>
      <div class="icon" style="background:#F9F0FF;color:#722ED1"><i class="fa fa-coins"></i></div>
    </div>
    <div class="value">$<?php echo number_format($totalValue,0); ?></div>
    <div class="sub">Lifetime overseas procurement</div>
  </div>
</div>

<!-- ── Charts Row 1 ── -->
<div class="opo-charts-grid">
  <div class="opo-chart-card">
    <h3><i class="fa fa-chart-pie"></i> Orders by Status</h3>
    <div class="opo-chart-wrap"><canvas id="opoStatusChart"></canvas></div>
  </div>
  <div class="opo-chart-card">
    <h3><i class="fa fa-chart-line"></i> Monthly Trend (12 Months)</h3>
    <div class="opo-chart-wrap"><canvas id="opoTrendChart"></canvas></div>
  </div>
  <div class="opo-chart-card">
    <h3><i class="fa fa-money-bill-wave"></i> Value by Currency</h3>
    <div class="opo-chart-wrap"><canvas id="opoCurrencyChart"></canvas></div>
  </div>
</div>

<!-- ── Charts Row 2 ── -->
<div class="opo-charts-grid">
  <div class="opo-chart-card">
    <h3><i class="fa fa-truck-loading"></i> Shipment Mode</h3>
    <div class="opo-chart-wrap"><canvas id="opoShipChart"></canvas></div>
  </div>
  <div class="opo-chart-card">
    <h3><i class="fa fa-building"></i> Top Suppliers by Value</h3>
    <div class="opo-chart-wrap"><canvas id="opoSuppChart"></canvas></div>
  </div>
  <div class="opo-chart-card">
    <h3><i class="fa fa-sitemap"></i> Orders by Department</h3>
    <div class="opo-chart-wrap"><canvas id="opoDeptChart"></canvas></div>
  </div>
</div>

<!-- ── Recent Orders ── -->
<div class="opo-recent-card">
  <h3><i class="fa fa-clock-rotate-left"></i> Recent Overseas Purchase Orders</h3>
  <div style="overflow-x:auto">
    <table class="opo-tbl">
      <thead>
        <tr>
          <th>OPO #</th>
          <th>Supplier</th>
          <th>Currency</th>
          <th>Items</th>
          <th>Value</th>
          <th>Shipment</th>
          <th>Status</th>
          <th>Ref/Quote #</th>
          <th>Created By</th>
          <th>Date</th>
        </tr>
      </thead>
      <tbody>
<?php
if(count($recentOrders) > 0){
    foreach($recentOrders as $ro){
        $statusClass = 'opo-badge-draft';
        if($ro['status']=='Approved') $statusClass = 'opo-badge-approved';
        elseif($ro['status']=='Printed') $statusClass = 'opo-badge-printed';
        elseif($ro['status']=='Received') $statusClass = 'opo-badge-received';
        $dateF = ($ro['entered_date']) ? date('d M Y', strtotime($ro['entered_date'])) : '-';
        $suppName = $ro['suppname'] ? $ro['suppname'] : '-';
        if(strlen($suppName)>30) $suppName = substr($suppName,0,27).'...';
        $quoteNo = $ro['quote_no'] ? $ro['quote_no'] : '-';
        echo '<tr>';
        echo '<td><span class="opo-pill">#'.$ro['id'].'</span></td>';
        echo '<td title="'.htmlspecialchars($ro['suppname']).'">'.$suppName.'</td>';
        echo '<td>'.$ro['currency'].'</td>';
        echo '<td style="text-align:center">'.$ro['item_count'].'</td>';
        echo '<td style="text-align:right;font-weight:600">$'.number_format($ro['total_val'],2).'</td>';
        echo '<td>'.$ro['shipment_mode'].'</td>';
        echo '<td><span class="opo-badge '.$statusClass.'">'.$ro['status'].'</span></td>';
        echo '<td>'.$quoteNo.'</td>';
        echo '<td>'.$ro['entered_by'].'</td>';
        echo '<td>'.$dateF.'</td>';
        echo '</tr>';
    }
} else {
    echo '<tr><td colspan="10" style="text-align:center;padding:24px;color:var(--opo-muted)"><i class="fa fa-inbox" style="font-size:24px;display:block;margin-bottom:8px"></i>No orders found</td></tr>';
}
?>
      </tbody>
    </table>
  </div>
</div>

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

<!-- ── Xcrud Table (100% Preserved) ── -->
<div class="opo-xcrud-wrap">
<div class="col-sm-12">
<?php
    include('xcrud/xcrud.php');
    $ebusiness = Xcrud::get_instance();
	$ebusiness->table('overseas_purchase_orders');
	$ebusiness->show_primary_ai_column(true);
	$ebusiness->relation('supplier_name','suppliers','supplierid','suppname');
	$ebusiness->relation('currency','currencies','currency','currency');
	$ebusiness->relation('gl_code','oldglcode','oldglcode',array('name','oldglcode'));
	$ebusiness->relation('department','department','departmentid','departmentname');
	$ebusiness->label('id','OPO No:');
	$ebusiness->pass_default('entered_by',$userid);
	$ebusiness->pass_var('entered_by',$userid);
	$timenow = date('Y-m-d H:i:s');
	$ebusiness->pass_default('entered_date',$timenow);
	$ebusiness->pass_var('entered_date',$timenow);
	$ebusiness->disabled('entered_by,entered_date');
	$log = "Entered by: ".$userid." Date : ".$timenow;
	$ebusiness->pass_default('log',$log);
	$ebusiness->pass_var('log',$log);
	$ebusiness->before_update('update_logoverseas');
	$ebusiness->unset_remove();
	$ebusiness->change_type('shipment_mode','select','Air Freight','Air Freight,Sea Freight,Electronic');
	$ebusiness->change_type('status','select','Draft','Draft,Approved,Printed,Received');
	$ebusiness->order_by('id','desc');
	$ebusiness->button('ImportLineItemsOPO.php?id={id}', 'Import Lineitems from CSV','glyphicon glyphicon-upload','westpac');
	$ebusiness->button('SendApprovalOPO.php?id={id}', 'Send for Approval','glyphicon glyphicon-envelope','westpac');
	$ebusiness->button('PrintOPO.php?id={id}', 'Print OPO','glyphicon glyphicon-download-alt','westpac');
	
	$attachements = $ebusiness->nested_table('Overseas Purchase Order Attachments','id','overseas_purchase_orders_attachments','id');
	
	$details = $ebusiness->nested_table('Overseas Purchase Order Details','id','overseas_purchase_orders_details','id');
	$details->relation('erp_stockid','stockmaster','stockid',array('stockid','description'));
	$details->relation('department','department','departmentid','departmentname');
	$details->relation('gl_code','oldglcode','oldglcode',array('name','oldglcode'));
	$details->pass_default('entered_by',$userid);
	$details->pass_var('entered_by',$userid);
	$timenow = date('Y-m-d H:i:s');
	$details->pass_default('entered_date',$timenow);
	$details->pass_var('entered_date',$timenow);
	$details->disabled('entered_by,entered_date');
	$details->change_type('shipment_mode','select','Air Freight','Air Freight,Sea Freight,Electronic');
	$details->set_attr('qty',array('id'=>'qty'));
	$details->set_attr('unit_price',array('id'=>'price'));
	$details->set_attr('total_price',array('id'=>'tprice'));
	$details->label('id','OPO No:');
	$details->sum('total_price');
	
	echo $ebusiness->render();
?>
</div>
</div>

<?php
} else {
    echo '<div style="text-align:center;padding:60px;font-family:Poppins,sans-serif">';
    echo '<i class="fa fa-lock" style="font-size:48px;color:#D1D5DB;display:block;margin-bottom:16px"></i>';
    echo '<p style="font-size:16px;color:var(--opo-text);font-weight:600">Access Restricted</p>';
    echo '<p style="color:var(--opo-muted)">You are not authorised to view Overseas Purchase Orders. Contact Admin.</p>';
    echo '</div>';
}
?>

</div><!-- end page wrapper -->

<script>
/* ── Dashboard Toggle ── */
function toggleOpoDash(){
    var dash = document.getElementById('opoDashboard');
    var icon = document.getElementById('opoDashIcon');
    var toggle = document.getElementById('opoDashToggle');
    var collapsed = !dash.classList.contains('collapsed');
    dash.classList.toggle('collapsed');
    toggle.classList.toggle('collapsed');
    localStorage.setItem('opo_dash_collapsed', collapsed ? '1' : '0');
}
(function(){
    if(localStorage.getItem('opo_dash_collapsed')==='1'){
        document.getElementById('opoDashboard').classList.add('collapsed');
        document.getElementById('opoDashToggle').classList.add('collapsed');
    }
})();

/* ── Chart.js Defaults ── */
Chart.defaults.font.family = "'Poppins',sans-serif";
Chart.defaults.font.size = 11;
Chart.defaults.animation = false;
Chart.defaults.plugins.legend.labels.boxWidth = 12;

/* ── Status Doughnut ── */
new Chart(document.getElementById('opoStatusChart'),{
    type:'doughnut',
    data:{
        labels:['Draft','Approved','Printed','Received'],
        datasets:[{
            data:[<?php echo $statusData['Draft']['cnt'].','.$statusData['Approved']['cnt'].','.$statusData['Printed']['cnt'].','.$statusData['Received']['cnt']; ?>],
            backgroundColor:['#FAAD14','#1890FF','#52C41A','#8C8C8C'],
            borderWidth:2,borderColor:'#fff'
        }]
    },
    options:{responsive:true,maintainAspectRatio:false,cutout:'60%',
        plugins:{legend:{position:'right',labels:{padding:12,font:{size:11}}}}}
});

/* ── Monthly Trend ── */
new Chart(document.getElementById('opoTrendChart'),{
    type:'bar',
    data:{
        labels:<?php echo json_encode($trendLabels); ?>,
        datasets:[
            {label:'Orders',data:<?php echo json_encode($trendCounts); ?>,backgroundColor:'rgba(42,171,179,.7)',borderRadius:4,yAxisID:'y',maxBarThickness:24},
            {label:'Value ($)',data:<?php echo json_encode($trendValues); ?>,type:'line',borderColor:'#FF6B6B',backgroundColor:'rgba(255,107,107,.1)',borderWidth:2,pointRadius:3,yAxisID:'y1',tension:.3}
        ]
    },
    options:{responsive:true,maintainAspectRatio:false,
        plugins:{legend:{position:'top',labels:{padding:8,font:{size:10}}}},
        scales:{
            y:{position:'left',grid:{display:false},ticks:{font:{size:10}}},
            y1:{position:'right',grid:{drawOnChartArea:false},ticks:{font:{size:10},callback:function(v){return '$'+v.toLocaleString()}}},
            x:{grid:{display:false},ticks:{font:{size:9},maxRotation:45}}
        }
    }
});

/* ── Currency Bar ── */
new Chart(document.getElementById('opoCurrencyChart'),{
    type:'bar',
    data:{
        labels:<?php echo json_encode($currencyLabels); ?>,
        datasets:[{data:<?php echo json_encode($currencyValues); ?>,backgroundColor:['#2AABB3','#1890FF','#722ED1','#FAAD14','#52C41A','#FF4D4F'],borderRadius:6,maxBarThickness:32}]
    },
    options:{responsive:true,maintainAspectRatio:false,indexAxis:'y',
        plugins:{legend:{display:false}},
        scales:{x:{grid:{display:false},ticks:{font:{size:10},callback:function(v){return '$'+v.toLocaleString()}}},y:{grid:{display:false},ticks:{font:{size:10}}}}}
});

/* ── Shipment Doughnut ── */
new Chart(document.getElementById('opoShipChart'),{
    type:'doughnut',
    data:{
        labels:<?php echo json_encode($shipLabels); ?>,
        datasets:[{data:<?php echo json_encode($shipValues); ?>,backgroundColor:['#2AABB3','#1890FF','#722ED1','#FAAD14'],borderWidth:2,borderColor:'#fff'}]
    },
    options:{responsive:true,maintainAspectRatio:false,cutout:'55%',
        plugins:{legend:{position:'right',labels:{padding:12,font:{size:11}}}}}
});

/* ── Top Suppliers Horizontal Bar ── */
new Chart(document.getElementById('opoSuppChart'),{
    type:'bar',
    data:{
        labels:<?php echo json_encode($suppLabels); ?>,
        datasets:[{label:'Value ($)',data:<?php echo json_encode($suppValues); ?>,backgroundColor:'rgba(30,143,150,.75)',borderRadius:6,maxBarThickness:22}]
    },
    options:{responsive:true,maintainAspectRatio:false,indexAxis:'y',
        plugins:{legend:{display:false}},
        scales:{x:{grid:{display:false},ticks:{font:{size:10},callback:function(v){return '$'+v.toLocaleString()}}},y:{grid:{display:false},ticks:{font:{size:10}}}}}
});

/* ── Department Bar ── */
new Chart(document.getElementById('opoDeptChart'),{
    type:'bar',
    data:{
        labels:<?php echo json_encode($deptLabels); ?>,
        datasets:[{data:<?php echo json_encode($deptValues); ?>,backgroundColor:['#2AABB3','#1890FF','#722ED1','#52C41A','#FAAD14','#FF4D4F'],borderRadius:6,maxBarThickness:28}]
    },
    options:{responsive:true,maintainAspectRatio:false,
        plugins:{legend:{display:false}},
        scales:{x:{grid:{display:false},ticks:{font:{size:9},maxRotation:45}},y:{grid:{display:false},ticks:{font:{size:10},stepSize:1}}}}
});

/* ── Auto-calculate total_price in nested details ── */
jQuery(document).ready(function($){
    $(".xcrud").on("blur","#qty,#price",function(){
        var qty = parseFloat($("#qty").val()) || 0;
        var price = parseFloat($("#price").val()) || 0;
        $("#tprice").val((qty * price).toFixed(2));
    });
});

/* ── Dismiss Loading Modal ── */
document.getElementById('opoLoadingOverlay').classList.add('fade-out');
setTimeout(function(){ document.getElementById('opoLoadingOverlay').style.display='none'; }, 600);
</script>

<?php
echo '</div>'; // close col-sm-12 wrapper from newheader
echo '</div>';
?>

</div></div></div>

<div id="m_scroll_top" class="m-scroll-top"><i class="la la-arrow-up"></i></div>
<script src="includes/vendors/owl.carousel/dist/owl.carousel.js" type="text/javascript"></script>
</body>
</html>
