<?php
/* Stock Request - Enhanced with Ant Design Dashboard (v2 - Fixed KPIs + Stock Analytics) */
error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity=0;

include('includes/session.inc');
$Title=_('Stock Requests');
include('includes/newheader.php');

$userid = $_SESSION['UserID'];

/* ── Direct DB connection for dashboard queries ── */
$dash_conn = new mysqli('localhost', 'sooggoo', '4Compassion*', 'evergreenint');
if ($dash_conn->connect_error) { $dash_conn = null; }

/* ── Dashboard Data ── */
$total_requests = 0;
$pending_requests = 0;
$completed_requests = 0;
$authorised_requests = 0;
$this_month_requests = 0;
$total_items = 0;
$dept_data = array();
$monthly_data = array();
$top_requestors = array();
$recent_requests = array();
$top_items = array();
$item_category_data = array();
$monthly_qty_data = array();
$avg_items_per_request = 0;
$unique_items_count = 0;
$total_qty_dispatched = 0;
$top_items_this_month = array();

if ($dash_conn) {
    $dept_filter = '';
    if ($userid == 'schand' || $userid == 'stephanie' || $userid == 'waqa') {
        $dept_filter = ' AND s.departmentid = 6';
    } elseif ($userid == 'serge' || $userid == 'ranjeeta') {
        $dept_filter = ' AND s.departmentid = 18';
    } elseif ($userid == 'nisha') {
        $dept_filter = ' AND s.departmentid = 7';
    } elseif ($userid == 'lusi') {
        $dept_filter = " AND s.departmentid IN (9,10)";
    } elseif ($userid == 'riaz') {
        $dept_filter = ' AND s.departmentid = 10';
    } elseif ($userid == 'mike') {
        $dept_filter = " AND s.departmentid IN (9,10)";
    } elseif ($userid == 'rajnesh') {
        $dept_filter = ' AND s.departmentid = 3';
    } elseif ($userid == 'rowen' || $userid == 'rramlu') {
        $dept_filter = " AND s.departmentid IN (8,21)";
    } elseif ($userid == 'vani' || $userid == 'ruth' || $userid == 'ronil' || $userid == 'roneelp' || $userid == 'saula') {
        $dept_filter = " AND s.departmentid IN (2,7,10,14,16,19,23,29)";
    } elseif ($userid == 'ilimo' || $userid == 'jokaveti') {
        $dept_filter = ' AND s.departmentid = 1';
    } elseif ($userid == 'mere' || $userid == 'sureta' || $userid == 'lina' || $userid == 'crispus' || $userid == 'mereseini') {
        $dept_filter = " AND s.departmentid IN (9,11)";
    }

    /* ─── FIX: Use CAST to prevent MySQL implicit type coercion ───
       Bug: When 'closed' is INT, comparing "closed = 'Yes'" makes MySQL convert
       'Yes' → 0, matching ALL rows where closed=0 (pending). Same for authorised.
       Fix: CAST(closed AS CHAR) forces proper string comparison. */
    $r = $dash_conn->query("SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN s.closed = 1 OR CAST(s.closed AS CHAR) = 'Yes' THEN 1 ELSE 0 END) as completed,
        SUM(CASE WHEN s.authorised = 1 OR CAST(s.authorised AS CHAR) = 'Yes' THEN 1 ELSE 0 END) as authorised,
        SUM(CASE WHEN MONTH(s.despatchdate) = MONTH(CURDATE()) AND YEAR(s.despatchdate) = YEAR(CURDATE()) THEN 1 ELSE 0 END) as this_month
        FROM stockrequest s WHERE 1=1 $dept_filter");
    if ($r) { 
        $row = $r->fetch_assoc(); 
        $total_requests = (int)$row['total']; 
        $completed_requests = (int)$row['completed']; 
        $authorised_requests = (int)$row['authorised']; 
        $this_month_requests = (int)$row['this_month']; 
    }
    $pending_requests = $total_requests - $completed_requests;

    /* Total line items + stock stats */
    $r = $dash_conn->query("SELECT COUNT(*) as cnt, COUNT(DISTINCT si.stockid) as unique_items, COALESCE(SUM(si.quantity),0) as total_qty
        FROM stockrequestitems si INNER JOIN stockrequest s ON si.dispatchid = s.dispatchid WHERE 1=1 $dept_filter");
    if ($r) { 
        $row = $r->fetch_assoc(); 
        $total_items = (int)$row['cnt']; 
        $unique_items_count = (int)$row['unique_items'];
        $total_qty_dispatched = (float)$row['total_qty'];
    }
    $avg_items_per_request = ($total_requests > 0) ? round($total_items / $total_requests, 1) : 0;

    /* Department breakdown */
    $r = $dash_conn->query("SELECT d.departmentname, COUNT(*) as cnt 
        FROM stockrequest s LEFT JOIN department d ON s.departmentid = d.departmentid 
        WHERE 1=1 $dept_filter GROUP BY s.departmentid, d.departmentname ORDER BY cnt DESC LIMIT 6");
    if ($r) { while ($row = $r->fetch_assoc()) { $dept_data[] = $row; } }

    /* Monthly trend */
    $r = $dash_conn->query("SELECT DATE_FORMAT(s.despatchdate, '%Y-%m') as mth, 
        DATE_FORMAT(s.despatchdate, '%b') as label, COUNT(*) as cnt
        FROM stockrequest s WHERE s.despatchdate >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH) $dept_filter
        GROUP BY mth, label ORDER BY mth ASC");
    if ($r) { while ($row = $r->fetch_assoc()) { $monthly_data[] = $row; } }

    /* Top requestors */
    $r = $dash_conn->query("SELECT s.initiator, COUNT(*) as cnt 
        FROM stockrequest s WHERE s.initiator IS NOT NULL AND s.initiator != '' $dept_filter
        GROUP BY s.initiator ORDER BY cnt DESC LIMIT 5");
    if ($r) { while ($row = $r->fetch_assoc()) { $top_requestors[] = $row; } }

    /* Recent requests */
    $r = $dash_conn->query("SELECT s.dispatchid, s.despatchdate, s.narrative, s.closed, s.authorised, d.departmentname,
        CONCAT(e.first_name, ' ', e.last_name) as receiver_name
        FROM stockrequest s LEFT JOIN department d ON s.departmentid = d.departmentid
        LEFT JOIN employeemaster e ON s.employee = e.employeeid
        WHERE 1=1 $dept_filter ORDER BY s.dispatchid DESC LIMIT 5");
    if ($r) { while ($row = $r->fetch_assoc()) { $recent_requests[] = $row; } }

    /* ─── NEW: Stock Item Analytics (from nested stockrequestitems) ─── */

    /* Top 10 most frequently requested items (all time) */
    $r = $dash_conn->query("SELECT si.stockid, sm.description, 
        COUNT(*) as request_count, COALESCE(SUM(si.quantity),0) as total_qty
        FROM stockrequestitems si 
        INNER JOIN stockrequest s ON si.dispatchid = s.dispatchid
        LEFT JOIN stockmaster sm ON si.stockid = sm.stockid
        WHERE 1=1 $dept_filter
        GROUP BY si.stockid, sm.description 
        ORDER BY request_count DESC LIMIT 10");
    if ($r) { while ($row = $r->fetch_assoc()) { $top_items[] = $row; } }

    /* Top 10 items requested this month */
    $r = $dash_conn->query("SELECT si.stockid, sm.description, 
        COUNT(*) as request_count, COALESCE(SUM(si.quantity),0) as total_qty
        FROM stockrequestitems si 
        INNER JOIN stockrequest s ON si.dispatchid = s.dispatchid
        LEFT JOIN stockmaster sm ON si.stockid = sm.stockid
        WHERE MONTH(s.despatchdate) = MONTH(CURDATE()) AND YEAR(s.despatchdate) = YEAR(CURDATE()) $dept_filter
        GROUP BY si.stockid, sm.description 
        ORDER BY request_count DESC LIMIT 10");
    if ($r) { while ($row = $r->fetch_assoc()) { $top_items_this_month[] = $row; } }

    /* Item category/group breakdown */
    $r = $dash_conn->query("SELECT COALESCE(sm.categoryid, 'Uncategorised') as cat, 
        COUNT(*) as cnt, COALESCE(SUM(si.quantity),0) as total_qty
        FROM stockrequestitems si 
        INNER JOIN stockrequest s ON si.dispatchid = s.dispatchid
        LEFT JOIN stockmaster sm ON si.stockid = sm.stockid
        WHERE 1=1 $dept_filter
        GROUP BY cat ORDER BY cnt DESC LIMIT 8");
    if ($r) { while ($row = $r->fetch_assoc()) { $item_category_data[] = $row; } }

    /* Monthly quantity dispatched (last 6 months) */
    $r = $dash_conn->query("SELECT DATE_FORMAT(s.despatchdate, '%Y-%m') as mth,
        DATE_FORMAT(s.despatchdate, '%b') as label,
        COUNT(DISTINCT si.stockid) as unique_items,
        COALESCE(SUM(si.quantity),0) as total_qty
        FROM stockrequestitems si 
        INNER JOIN stockrequest s ON si.dispatchid = s.dispatchid
        WHERE s.despatchdate >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH) $dept_filter
        GROUP BY mth, label ORDER BY mth ASC");
    if ($r) { while ($row = $r->fetch_assoc()) { $monthly_qty_data[] = $row; } }

    $dash_conn->close();
}

$dept_labels = array(); $dept_counts = array();
foreach ($dept_data as $d) { 
    $name = isset($d['departmentname']) ? $d['departmentname'] : 'Unknown';
    if (strlen($name) > 18) { $name = substr($name, 0, 16) . '..'; }
    $dept_labels[] = $name; 
    $dept_counts[] = (int)$d['cnt']; 
}
$month_labels = array(); $month_counts = array();
foreach ($monthly_data as $m) { $month_labels[] = $m['label']; $month_counts[] = (int)$m['cnt']; }

/* Stock analytics arrays for charts */
$top_item_labels = array(); $top_item_counts = array(); $top_item_qtys = array();
foreach ($top_items as $ti) {
    $desc = isset($ti['description']) ? $ti['description'] : $ti['stockid'];
    if (strlen($desc) > 25) { $desc = substr($desc, 0, 23) . '..'; }
    $top_item_labels[] = $desc;
    $top_item_counts[] = (int)$ti['request_count'];
    $top_item_qtys[] = (float)$ti['total_qty'];
}

$cat_labels = array(); $cat_counts = array();
foreach ($item_category_data as $c) {
    $cl = isset($c['cat']) ? $c['cat'] : 'Unknown';
    if (strlen($cl) > 18) { $cl = substr($cl, 0, 16) . '..'; }
    $cat_labels[] = $cl;
    $cat_counts[] = (int)$c['cnt'];
}

$qty_month_labels = array(); $qty_month_vals = array(); $qty_unique_vals = array();
foreach ($monthly_qty_data as $mq) {
    $qty_month_labels[] = $mq['label'];
    $qty_month_vals[] = (float)$mq['total_qty'];
    $qty_unique_vals[] = (int)$mq['unique_items'];
}

$completion_rate = ($total_requests > 0) ? round(($completed_requests / $total_requests) * 100) : 0;
$auth_rate = ($total_requests > 0) ? round(($authorised_requests / $total_requests) * 100) : 0;
?>

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

<style>
:root {
    --sr-primary: #2AABB3;
    --sr-primary-dark: #1E8F96;
    --sr-primary-darker: #187278;
    --sr-primary-light: #E6F7F8;
    --sr-success: #52C41A;
    --sr-warning: #FAAD14;
    --sr-danger: #FF4D4F;
    --sr-info: #1890FF;
    --sr-purple: #722ED1;
    --sr-border: #E5E7EB;
    --sr-text: #1F2937;
    --sr-text-sec: #6B7280;
    --sr-white: #FFFFFF;
    --sr-shadow: 0 1px 3px rgba(0,0,0,0.08);
    --sr-shadow-md: 0 4px 12px rgba(0,0,0,0.1);
    --sr-radius: 10px;
}
* { font-family: 'Poppins', sans-serif; }

.sr-banner {
    background: linear-gradient(135deg, var(--sr-primary-darker) 0%, var(--sr-primary) 50%, #3CC0C8 100%);
    border-radius: var(--sr-radius); padding: 22px 28px; margin: 0 0 14px 0;
    color: #fff; position: relative; overflow: hidden;
}
.sr-banner::before { content:''; position:absolute; top:-40px; right:-40px; width:180px; height:180px; border-radius:50%; background:rgba(255,255,255,0.06); }
.sr-banner h2 { margin:0 0 3px 0; font-size:20px; font-weight:600; color:#fff; }
.sr-banner-sub { font-size:12px; opacity:0.85; margin:0; }
.sr-breadcrumb { margin-top:6px; font-size:11px; opacity:0.7; }
.sr-breadcrumb a { color:#fff; text-decoration:none; }
.sr-banner-actions { position:absolute; right:28px; top:50%; transform:translateY(-50%); z-index:2; }
.sr-btn-create {
    background:rgba(255,255,255,0.2); border:1px solid rgba(255,255,255,0.35);
    color:#fff; padding:8px 18px; border-radius:6px; font-size:12px; font-weight:500;
    cursor:pointer; text-decoration:none; transition:all 0.2s;
    display:inline-flex; align-items:center; gap:6px;
}
.sr-btn-create:hover { background:rgba(255,255,255,0.3); color:#fff; text-decoration:none; }

.sr-dash-toggle {
    display:flex; align-items:center; gap:8px; margin-bottom:10px;
    cursor:pointer; user-select:none; font-size:13px; color:var(--sr-primary-dark); font-weight:500;
}
.sr-dash-toggle i.toggle-icon { transition:transform 0.3s; font-size:11px; }
.sr-dash-toggle.collapsed i.toggle-icon { transform:rotate(-90deg); }
.sr-dashboard { transition:max-height 0.4s ease, opacity 0.3s ease; overflow:hidden; }
.sr-dashboard.collapsed { max-height:0 !important; opacity:0; margin-bottom:0; }

.sr-kpi-strip { display:grid; grid-template-columns:repeat(7,1fr); gap:10px; margin-bottom:12px; }
@media (max-width:1200px) { .sr-kpi-strip { grid-template-columns:repeat(4,1fr); } }
@media (max-width:768px) { .sr-kpi-strip { grid-template-columns:repeat(2,1fr); } }

.sr-kpi-card {
    background:var(--sr-white); border-radius:8px; padding:12px; border:1px solid var(--sr-border);
    border-left:3px solid var(--sr-primary); box-shadow:var(--sr-shadow);
    display:flex; align-items:center; gap:10px; transition:box-shadow 0.2s,transform 0.15s;
}
.sr-kpi-card:hover { box-shadow:var(--sr-shadow-md); transform:translateY(-1px); }
.sr-kpi-card.success { border-left-color:var(--sr-success); }
.sr-kpi-card.warning { border-left-color:var(--sr-warning); }
.sr-kpi-card.danger  { border-left-color:var(--sr-danger); }
.sr-kpi-card.info    { border-left-color:var(--sr-info); }
.sr-kpi-card.purple  { border-left-color:var(--sr-purple); }

.sr-kpi-icon {
    width:34px; height:34px; border-radius:8px;
    display:flex; align-items:center; justify-content:center; font-size:14px; flex-shrink:0;
}
.sr-kpi-icon.teal   { background:var(--sr-primary-light); color:var(--sr-primary-dark); }
.sr-kpi-icon.green  { background:#F0FFF0; color:var(--sr-success); }
.sr-kpi-icon.orange { background:#FFF8E6; color:var(--sr-warning); }
.sr-kpi-icon.blue   { background:#E6F4FF; color:var(--sr-info); }
.sr-kpi-icon.purple { background:#F3EEFF; color:var(--sr-purple); }
.sr-kpi-value { font-size:18px; font-weight:700; color:var(--sr-text); line-height:1.1; }
.sr-kpi-label { font-size:9px; color:var(--sr-text-sec); text-transform:uppercase; letter-spacing:0.3px; }

.sr-row-3 { display:grid; grid-template-columns:1fr 1fr 1fr; gap:12px; margin-bottom:12px; }
@media (max-width:1100px) { .sr-row-3 { grid-template-columns:1fr 1fr; } }
@media (max-width:768px) { .sr-row-3 { grid-template-columns:1fr; } }

.sr-row-2 { display:grid; grid-template-columns:1fr 1fr; gap:12px; margin-bottom:12px; }
@media (max-width:900px) { .sr-row-2 { grid-template-columns:1fr; } }

.sr-card {
    background:var(--sr-white); border-radius:8px; border:1px solid var(--sr-border);
    box-shadow:var(--sr-shadow); padding:14px 16px;
}
.sr-card-title {
    font-size:11px; font-weight:600; color:var(--sr-text); margin:0 0 8px 0;
    display:flex; align-items:center; gap:6px; text-transform:uppercase; letter-spacing:0.3px;
}
.sr-card-title i { color:var(--sr-primary); font-size:12px; }
.sr-card-subtitle { font-size:10px; color:var(--sr-text-sec); margin:-4px 0 8px 0; font-weight:400; }

.sr-chart-box { height:200px; max-height:200px; overflow:hidden; position:relative; }
.sr-chart-box-tall { height:280px; max-height:280px; overflow:hidden; position:relative; }

.sr-compact-table { width:100%; border-collapse:collapse; font-size:11px; }
.sr-compact-table th {
    background:#F8FAFB; padding:6px 8px; text-align:left; font-weight:600;
    color:var(--sr-text-sec); border-bottom:1px solid var(--sr-border);
    font-size:10px; text-transform:uppercase; letter-spacing:0.4px;
}
.sr-compact-table td { padding:7px 8px; border-bottom:1px solid #F3F4F6; color:var(--sr-text); }
.sr-compact-table tr:last-child td { border-bottom:none; }
.sr-compact-table tr:hover td { background:var(--sr-primary-light); }

.sr-badge { display:inline-block; padding:1px 8px; border-radius:10px; font-size:10px; font-weight:500; }
.sr-badge-success { background:#F0FFF0; color:#389E0D; }
.sr-badge-warning { background:#FFF8E6; color:#D48806; }
.sr-badge-danger  { background:#FFF0F0; color:#CF1322; }

.sr-progress-row { margin-bottom:10px; }
.sr-progress-label { display:flex; justify-content:space-between; font-size:11px; color:var(--sr-text-sec); margin-bottom:4px; }
.sr-progress-bar { height:6px; background:#F3F4F6; border-radius:3px; overflow:hidden; }
.sr-progress-fill { height:100%; border-radius:3px; transition:width 0.8s ease; }

.sr-rank-item { display:flex; align-items:center; gap:8px; padding:5px 0; border-bottom:1px solid #F3F4F6; }
.sr-rank-item:last-child { border-bottom:none; }
.sr-rank-num {
    width:22px; height:22px; border-radius:50%; background:var(--sr-primary-light);
    color:var(--sr-primary-dark); display:flex; align-items:center; justify-content:center;
    font-size:10px; font-weight:700; flex-shrink:0;
}
.sr-rank-name { flex:1; font-size:11px; color:var(--sr-text); font-weight:500; }
.sr-rank-count { font-size:11px; font-weight:600; color:var(--sr-primary-dark); }

/* Mini stat boxes */
.sr-mini-stats { display:grid; grid-template-columns:1fr 1fr 1fr; gap:8px; margin-bottom:10px; }
.sr-mini-stat { background:#F8FAFB; border-radius:6px; padding:8px 10px; text-align:center; border:1px solid #F0F1F3; }
.sr-mini-stat-val { font-size:16px; font-weight:700; color:var(--sr-primary-dark); line-height:1.2; }
.sr-mini-stat-lbl { font-size:9px; color:var(--sr-text-sec); text-transform:uppercase; letter-spacing:0.3px; }

/* Tab switcher */
.sr-tabs { display:flex; gap:0; margin-bottom:10px; border-bottom:2px solid #F3F4F6; }
.sr-tab {
    padding:6px 14px; font-size:11px; font-weight:500; color:var(--sr-text-sec);
    cursor:pointer; border-bottom:2px solid transparent; margin-bottom:-2px; transition:all 0.2s;
    user-select:none;
}
.sr-tab:hover { color:var(--sr-primary-dark); }
.sr-tab.active { color:var(--sr-primary-dark); border-bottom-color:var(--sr-primary); font-weight:600; }
.sr-tab-content { display:none; }
.sr-tab-content.active { display:block; }

/* Item frequency bar in table */
.sr-freq-bar { height:4px; background:#F3F4F6; border-radius:2px; margin-top:3px; min-width:40px; }
.sr-freq-fill { height:100%; border-radius:2px; background:var(--sr-primary); transition:width 0.6s ease; }

.sr-loading-overlay {
    position:fixed; top:0; left:0; right:0; bottom:0;
    background:rgba(255,255,255,0.85); display:flex; align-items:center; justify-content:center;
    z-index:9999; transition:opacity 0.4s;
}
.sr-loading-overlay.fade-out { opacity:0; pointer-events:none; }
.sr-loading-box { background:var(--sr-white); border-radius:12px; padding:30px 42px; box-shadow:0 8px 30px rgba(0,0,0,0.12); text-align:center; }
.sr-spinner { width:36px; height:36px; border:3px solid #E5E7EB; border-top:3px solid var(--sr-primary); border-radius:50%; animation:sr-spin 0.8s linear infinite; margin:0 auto 12px; }
@keyframes sr-spin { to { transform:rotate(360deg); } }
.sr-loading-text { font-size:13px; color:var(--sr-text-sec); font-weight:500; }

.sr-section-label { font-size:13px; font-weight:600; color:var(--sr-text); margin:0 0 10px 0; display:flex; align-items:center; gap:8px; }
.sr-section-label i { color:var(--sr-primary); }

/* XCRUD Overlay */
.xcrud-container { margin-top:0 !important; }
.xcrud-nav { background:var(--sr-white) !important; border-radius:8px !important; border:1px solid var(--sr-border) !important; }
table.xcrud-list { border-collapse:collapse !important; }
table.xcrud-list thead tr { background:linear-gradient(135deg, var(--sr-primary-darker), var(--sr-primary)) !important; }
table.xcrud-list thead th { color:#fff !important; font-family:'Poppins',sans-serif !important; font-size:11px !important; font-weight:600 !important; padding:9px 10px !important; text-transform:uppercase !important; letter-spacing:0.4px !important; border:none !important; }
table.xcrud-list thead th a { color:#fff !important; }
table.xcrud-list tbody tr { transition:background 0.15s !important; }
table.xcrud-list tbody tr:hover { background:var(--sr-primary-light) !important; }
table.xcrud-list tbody td { font-family:'Poppins',sans-serif !important; font-size:11px !important; padding:8px 10px !important; color:var(--sr-text) !important; border-bottom:1px solid #F3F4F6 !important; }
table.xcrud-list tbody tr:nth-child(even) { background:#FAFBFC !important; }
table.xcrud-list tbody tr:nth-child(even):hover { background:var(--sr-primary-light) !important; }
.xcrud-top-actions a,.xcrud-action,.xcrud-top-actions button { font-family:'Poppins',sans-serif !important; border-radius:5px !important; }
.xcrud-pagination a,.xcrud-pagination span { border-radius:5px !important; font-family:'Poppins',sans-serif !important; }
.xcrud-pagination a.active,.xcrud-pagination span.current { background:var(--sr-primary) !important; color:#fff !important; }
</style>

<div class="sr-loading-overlay" id="srLoadingModal">
    <div class="sr-loading-box"><div class="sr-spinner"></div><div class="sr-loading-text">Loading Stock Requests...</div></div>
</div>

<?php ob_flush(); flush(); ?>

<div style="padding:0 6px;">

<div class="sr-banner">
    <h2><i class="fas fa-boxes-stacked" style="margin-right:8px;"></i>Stock Requests</h2>
    <p class="sr-banner-sub">Manage and track internal stock requests, authorisations & dispatches</p>
    <div class="sr-breadcrumb"><a href="index.php">Home</a> &nbsp;/&nbsp; Inventory &nbsp;/&nbsp; Stock Requests</div>
    <div class="sr-banner-actions"><a href="InternalStockRequest.php" class="sr-btn-create"><i class="fas fa-plus-circle"></i> New Request</a></div>
</div>

<div class="sr-dash-toggle" id="srDashToggle" onclick="toggleSRDash()">
    <i class="fas fa-chevron-down toggle-icon"></i><span>Dashboard Metrics</span>
</div>

<div class="sr-dashboard" id="srDashboard">

    <!-- KPI Strip -->
    <div class="sr-kpi-strip">
        <div class="sr-kpi-card">
            <div class="sr-kpi-icon teal"><i class="fas fa-clipboard-list"></i></div>
            <div><div class="sr-kpi-value"><?php echo number_format($total_requests); ?></div><div class="sr-kpi-label">Total</div></div>
        </div>
        <div class="sr-kpi-card warning">
            <div class="sr-kpi-icon orange"><i class="fas fa-clock"></i></div>
            <div><div class="sr-kpi-value"><?php echo number_format($pending_requests); ?></div><div class="sr-kpi-label">Pending</div></div>
        </div>
        <div class="sr-kpi-card success">
            <div class="sr-kpi-icon green"><i class="fas fa-check-circle"></i></div>
            <div><div class="sr-kpi-value"><?php echo number_format($completed_requests); ?></div><div class="sr-kpi-label">Completed</div></div>
        </div>
        <div class="sr-kpi-card info">
            <div class="sr-kpi-icon blue"><i class="fas fa-user-shield"></i></div>
            <div><div class="sr-kpi-value"><?php echo number_format($authorised_requests); ?></div><div class="sr-kpi-label">Authorised</div></div>
        </div>
        <div class="sr-kpi-card purple">
            <div class="sr-kpi-icon purple"><i class="fas fa-calendar-day"></i></div>
            <div><div class="sr-kpi-value"><?php echo number_format($this_month_requests); ?></div><div class="sr-kpi-label">This Month</div></div>
        </div>
        <div class="sr-kpi-card">
            <div class="sr-kpi-icon teal"><i class="fas fa-cubes"></i></div>
            <div><div class="sr-kpi-value"><?php echo number_format($total_items); ?></div><div class="sr-kpi-label">Line Items</div></div>
        </div>
        <div class="sr-kpi-card success">
            <div class="sr-kpi-icon green"><i class="fas fa-percent"></i></div>
            <div><div class="sr-kpi-value"><?php echo $completion_rate; ?>%</div><div class="sr-kpi-label">Complete</div></div>
        </div>
    </div>

    <!-- Row 1: Monthly Trend + Department + Rates & Requestors -->
    <div class="sr-row-3">
        <div class="sr-card">
            <div class="sr-card-title"><i class="fas fa-chart-bar"></i> Monthly Trend</div>
            <div class="sr-chart-box"><canvas id="srMonthlyChart"></canvas></div>
        </div>
        <div class="sr-card">
            <div class="sr-card-title"><i class="fas fa-building"></i> By Department</div>
            <div class="sr-chart-box"><canvas id="srDeptChart"></canvas></div>
        </div>
        <div class="sr-card">
            <div class="sr-card-title"><i class="fas fa-chart-pie"></i> Rates & Top Requestors</div>
            <div class="sr-progress-row">
                <div class="sr-progress-label"><span>Completion</span><span style="font-weight:600;color:var(--sr-success);"><?php echo $completion_rate; ?>%</span></div>
                <div class="sr-progress-bar"><div class="sr-progress-fill" style="width:<?php echo $completion_rate; ?>%;background:var(--sr-success);"></div></div>
            </div>
            <div class="sr-progress-row">
                <div class="sr-progress-label"><span>Authorisation</span><span style="font-weight:600;color:var(--sr-info);"><?php echo $auth_rate; ?>%</span></div>
                <div class="sr-progress-bar"><div class="sr-progress-fill" style="width:<?php echo $auth_rate; ?>%;background:var(--sr-info);"></div></div>
            </div>
            <div style="margin-top:8px;border-top:1px solid #F3F4F6;padding-top:6px;">
                <?php 
                $rank = 1;
                foreach ($top_requestors as $tr) {
                    echo '<div class="sr-rank-item">';
                    echo '<div class="sr-rank-num">' . $rank . '</div>';
                    echo '<div class="sr-rank-name">' . htmlspecialchars($tr['initiator']) . '</div>';
                    echo '<div class="sr-rank-count">' . number_format($tr['cnt']) . '</div>';
                    echo '</div>';
                    $rank++;
                }
                if (count($top_requestors) == 0) {
                    echo '<div style="text-align:center;color:#999;padding:8px;font-size:11px;">No data</div>';
                }
                ?>
            </div>
        </div>
    </div>

    <!-- ═══════════════════════════════════════════════════════ -->
    <!-- Stock Item Analytics Section                           -->
    <!-- ═══════════════════════════════════════════════════════ -->

    <!-- Stock Item Mini Stats -->
    <div class="sr-card" style="margin-bottom:12px;">
        <div class="sr-card-title"><i class="fas fa-box-open"></i> Stock Item Overview</div>
        <div class="sr-mini-stats">
            <div class="sr-mini-stat">
                <div class="sr-mini-stat-val"><?php echo number_format($unique_items_count); ?></div>
                <div class="sr-mini-stat-lbl">Unique Items</div>
            </div>
            <div class="sr-mini-stat">
                <div class="sr-mini-stat-val"><?php echo number_format($total_qty_dispatched); ?></div>
                <div class="sr-mini-stat-lbl">Total Qty Dispatched</div>
            </div>
            <div class="sr-mini-stat">
                <div class="sr-mini-stat-val"><?php echo $avg_items_per_request; ?></div>
                <div class="sr-mini-stat-lbl">Avg Items / Request</div>
            </div>
        </div>
    </div>

    <!-- Row 2: Top Items Chart + Category Breakdown + Qty Trend -->
    <div class="sr-row-3">
        <div class="sr-card">
            <div class="sr-card-title"><i class="fas fa-fire"></i> Most Requested Items</div>
            <div class="sr-card-subtitle">By number of requests (all time)</div>
            <div class="sr-chart-box-tall"><canvas id="srTopItemsChart"></canvas></div>
        </div>
        <div class="sr-card">
            <div class="sr-card-title"><i class="fas fa-tags"></i> By Stock Category</div>
            <div class="sr-card-subtitle">Line items grouped by category</div>
            <div class="sr-chart-box-tall"><canvas id="srCategoryChart"></canvas></div>
        </div>
        <div class="sr-card">
            <div class="sr-card-title"><i class="fas fa-chart-line"></i> Monthly Qty Dispatched</div>
            <div class="sr-card-subtitle">Quantity &amp; unique items (6 months)</div>
            <div class="sr-chart-box-tall"><canvas id="srQtyTrendChart"></canvas></div>
        </div>
    </div>

    <!-- Row 3: Top Items Table (All Time vs This Month) + Recent Requests -->
    <div class="sr-row-2">
        <div class="sr-card">
            <div class="sr-card-title"><i class="fas fa-ranking-star"></i> Frequently Requested Items</div>
            <div class="sr-tabs">
                <div class="sr-tab active" onclick="switchItemTab('alltime', this)">All Time</div>
                <div class="sr-tab" onclick="switchItemTab('thismonth', this)">This Month</div>
            </div>
            <div class="sr-tab-content active" id="srItemsAlltime">
                <table class="sr-compact-table">
                    <thead><tr><th>#</th><th>Item</th><th style="text-align:right;">Requests</th><th style="text-align:right;">Total Qty</th><th style="width:60px;">Freq</th></tr></thead>
                    <tbody>
                    <?php 
                    $max_freq = (count($top_items) > 0) ? (int)$top_items[0]['request_count'] : 1;
                    $rank = 1;
                    foreach ($top_items as $ti) {
                        $desc = isset($ti['description']) ? htmlspecialchars($ti['description']) : htmlspecialchars($ti['stockid']);
                        if (strlen($desc) > 35) { $desc = substr($desc, 0, 33) . '..'; }
                        $pct = round(((int)$ti['request_count'] / $max_freq) * 100);
                        echo '<tr>';
                        echo '<td><span class="sr-rank-num" style="width:20px;height:20px;font-size:9px;">'.$rank.'</span></td>';
                        echo '<td title="'.htmlspecialchars(isset($ti['description'])?$ti['description']:$ti['stockid']).'">'.$desc.'<br><span style="font-size:9px;color:#999;">'.$ti['stockid'].'</span></td>';
                        echo '<td style="text-align:right;font-weight:600;">'.number_format($ti['request_count']).'</td>';
                        echo '<td style="text-align:right;">'.number_format($ti['total_qty']).'</td>';
                        echo '<td><div class="sr-freq-bar"><div class="sr-freq-fill" style="width:'.$pct.'%;"></div></div></td>';
                        echo '</tr>';
                        $rank++;
                    }
                    if (count($top_items) == 0) {
                        echo '<tr><td colspan="5" style="text-align:center;color:#999;padding:14px;">No item data available</td></tr>';
                    }
                    ?>
                    </tbody>
                </table>
            </div>
            <div class="sr-tab-content" id="srItemsThismonth">
                <table class="sr-compact-table">
                    <thead><tr><th>#</th><th>Item</th><th style="text-align:right;">Requests</th><th style="text-align:right;">Total Qty</th><th style="width:60px;">Freq</th></tr></thead>
                    <tbody>
                    <?php 
                    $max_freq_m = (count($top_items_this_month) > 0) ? (int)$top_items_this_month[0]['request_count'] : 1;
                    $rank = 1;
                    foreach ($top_items_this_month as $ti) {
                        $desc = isset($ti['description']) ? htmlspecialchars($ti['description']) : htmlspecialchars($ti['stockid']);
                        if (strlen($desc) > 35) { $desc = substr($desc, 0, 33) . '..'; }
                        $pct = round(((int)$ti['request_count'] / $max_freq_m) * 100);
                        echo '<tr>';
                        echo '<td><span class="sr-rank-num" style="width:20px;height:20px;font-size:9px;">'.$rank.'</span></td>';
                        echo '<td title="'.htmlspecialchars(isset($ti['description'])?$ti['description']:$ti['stockid']).'">'.$desc.'<br><span style="font-size:9px;color:#999;">'.$ti['stockid'].'</span></td>';
                        echo '<td style="text-align:right;font-weight:600;">'.number_format($ti['request_count']).'</td>';
                        echo '<td style="text-align:right;">'.number_format($ti['total_qty']).'</td>';
                        echo '<td><div class="sr-freq-bar"><div class="sr-freq-fill" style="width:'.$pct.'%;"></div></div></td>';
                        echo '</tr>';
                        $rank++;
                    }
                    if (count($top_items_this_month) == 0) {
                        echo '<tr><td colspan="5" style="text-align:center;color:#999;padding:14px;">No requests this month yet</td></tr>';
                    }
                    ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="sr-card">
            <div class="sr-card-title"><i class="fas fa-history"></i> Recent Requests</div>
            <table class="sr-compact-table">
                <thead><tr><th>Req #</th><th>Date</th><th>Department</th><th>Receiver</th><th>Status</th><th>Auth</th></tr></thead>
                <tbody>
                    <?php if (count($recent_requests) > 0) {
                        foreach ($recent_requests as $rr) {
                            /* FIX: Use strict comparison to avoid PHP type coercion
                               In PHP 5.x, (0 == 'Yes') is TRUE because both cast to 0 */
                            $cv = isset($rr['closed']) ? $rr['closed'] : '';
                            $av = isset($rr['authorised']) ? $rr['authorised'] : '';
                            $is_closed = ($cv === 1 || $cv === '1' || $cv === 'Yes');
                            $is_auth   = ($av === 1 || $av === '1' || $av === 'Yes');
                            if ($is_closed) { $bc='sr-badge-success'; $bt='Done'; }
                            elseif ($is_auth) { $bc='sr-badge-warning'; $bt='Auth'; }
                            else { $bc='sr-badge-danger'; $bt='Pending'; }
                            $dn = isset($rr['departmentname']) ? $rr['departmentname'] : '-';
                            $rn = isset($rr['receiver_name']) ? trim($rr['receiver_name']) : '-';
                            if ($rn == '') $rn = '-';
                            $ab = $is_auth ? '<span class="sr-badge sr-badge-success">Yes</span>' : '<span class="sr-badge sr-badge-danger">No</span>';
                            echo '<tr>';
                            echo '<td><strong>#'.htmlspecialchars($rr['dispatchid']).'</strong></td>';
                            echo '<td>'.htmlspecialchars($rr['despatchdate']).'</td>';
                            echo '<td>'.htmlspecialchars($dn).'</td>';
                            echo '<td>'.htmlspecialchars($rn).'</td>';
                            echo '<td><span class="sr-badge '.$bc.'">'.$bt.'</span></td>';
                            echo '<td>'.$ab.'</td>';
                            echo '</tr>';
                        }
                    } else {
                        echo '<tr><td colspan="6" style="text-align:center;color:#999;padding:14px;">No recent requests</td></tr>';
                    } ?>
                </tbody>
            </table>
        </div>
    </div>

</div>

<div class="sr-section-label"><i class="fas fa-table"></i> All Stock Request Listings</div>

<div class="col-sm-12" style="padding:0;">
<?php
echo '<link href="' . $RootPath . '/css/evergreen2/default.css" rel="stylesheet" type="text/css" media="screen"/>';

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

if ($userid =='schand' ||$userid =='stephanie' ){
    $xcrud->where('departmentid=',6);
}
if ($userid =='waqa'){
    $xcrud->where('departmentid=',6);
}
if ($userid =='serge' || $userid =='ranjeeta' ){
    $xcrud->where('departmentid=',18);
}
if ($userid =='nisha'){
    $xcrud->where('departmentid=',7);
    $xcrud->unset_edit();
}
if ($userid =='lusi' ){
    $xcrud->where('departmentid', array('9','10'));
}
if ($userid =='riaz' ){
    $xcrud->where('departmentid',10);
}
if ($userid =='mike'){
    $xcrud->where('departmentid', array('9','10'));
    $xcrud->unset_edit();
}
if ($userid =='rajnesh'){
    $xcrud->where('departmentid=',3);
    $xcrud->unset_edit();
}
if ($userid =='rowen' || $userid =='rramlu'){
    $xcrud->where('departmentid', array('8','21'));
    $xcrud->unset_edit();
}
if ($userid =='vani' || $userid =='ruth' || $userid =='ronil' ||$userid =='roneelp'||$userid =='saula' ){
    $xcrud->where('departmentid', array('2','7','10','14','16','19','23','29'));
}
if ($userid =='ilimo' ||$userid =='jokaveti'){
    $xcrud->where('departmentid=',1);
}
if ($userid =='mere' ||$userid =='sureta' ||$userid =='lina' ||$userid =='crispus' ||$userid =='mereseini' ){
    $xcrud->where('departmentid=',array('9','11'));
}

$xcrud->table_name('All Stock Request Listings');
$xcrud->relation('departmentid','department','departmentid',array('departmentid','departmentname'));
$xcrud->relation('employee','employeemaster','employeeid',array('first_name','last_name','employeeid'));
$xcrud->relation('client','debtorsmaster','debtorno','name');
$xcrud->relation('jobno','projectdetails','projectid',array('project_name','wip_expense'));
$xcrud->order_by('dispatchid','desc');
$xcrud->unset_remove();
$xcrud->unset_add();

$xcrud->label('dispatchid','Request No');
$xcrud->label('employee','Receiver');
$xcrud->label('datetime','Authorised Time');
$xcrud->label('closed','Completed');
$xcrud->label('despatchdate','Date');

$xcrud->button('StockRequestPrint.php?dispatchid={dispatchid}&loccode={loccode}&departmentid={departmentid}&despatchdate={despatchdate}&jobno={jobno}&authorised={authorised}&authorized_by={authorized_by}&narrative{narrative}&initiator={initiator}&transtype={transtype}&producttype={producttype}&client={client}&account={account}&employee={employee}&datetime={datetime}', 'Print Request','glyphicon glyphicon-download-alt');

if ($userid =='admin' ||$userid =='mike'|| $userid =='douglas' || $userid =='losa'|| $userid =='ravi' ){
    $xcrud->button('StockRequestSign.php?dispatchid={dispatchid}&loccode={loccode}&departmentid={departmentid}&despatchdate={despatchdate}&jobno={jobno}&authorised={authorised}&authorized_by={authorized_by}&narrative{narrative}&initiator={initiator}&transtype={transtype}&producttype={producttype}&client={client}&account={account}&employee={employee}', 'Authorizers Signature','glyphicon glyphicon-pencil');
}

$xcrud->button('StockRequestSign1.php?dispatchid={dispatchid}&loccode={loccode}&departmentid={departmentid}&despatchdate={despatchdate}&jobno={jobno}&authorised={authorised}&authorized_by={authorized_by}&narrative{narrative}&initiator={initiator}&transtype={transtype}&producttype={producttype}&client={client}&account={account}&employee={employee}', 'Receivers Signature','glyphicon glyphicon-pencil');

$xcrud->column_pattern('dispatchid', '<a href="#" class="xcrud-action" data-task="view" data-primary="{dispatchid}">{value}</a>');

$stockrequestdetails = $xcrud->nested_table('Stock Request Details','dispatchid','stockrequestitems','dispatchid');
$stockrequestdetails->relation('stockid','stockmaster','stockid',array('stockid','description'));
$stockrequestdetails->disabled('dispatchitemsid,dispatchid');
$stockrequestdetails->unset_remove();

echo $xcrud->render();
?>
</div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    var lm = document.getElementById('srLoadingModal');
    if (lm) { lm.classList.add('fade-out'); setTimeout(function(){ lm.style.display='none'; }, 500); }

    if (localStorage.getItem('sr_dash_collapsed') === 'true') {
        document.getElementById('srDashboard').classList.add('collapsed');
        document.getElementById('srDashToggle').classList.add('collapsed');
    }

    var cf = { family:'Poppins', size:11 };
    var tt = { backgroundColor:'#1F2937', titleFont:{family:'Poppins'}, bodyFont:{family:'Poppins'}, cornerRadius:6 };

    // ═══ Monthly Trend — HORIZONTAL bar ═══
    new Chart(document.getElementById('srMonthlyChart'), {
        type: 'bar',
        data: {
            labels: <?php echo json_encode($month_labels); ?>,
            datasets: [{
                label: 'Requests',
                data: <?php echo json_encode($month_counts); ?>,
                backgroundColor: 'rgba(42,171,179,0.8)',
                borderColor: '#1E8F96', borderWidth: 1, borderRadius: 4, barThickness: 18
            }]
        },
        options: {
            indexAxis: 'y', responsive: true, maintainAspectRatio: false,
            plugins: { legend:{display:false}, tooltip:tt },
            scales: {
                x: { beginAtZero:true, grid:{color:'#F3F4F6'}, ticks:{font:cf, stepSize:1} },
                y: { grid:{display:false}, ticks:{font:cf} }
            }
        }
    });

    // ═══ Department — HORIZONTAL bar ═══
    var dc = ['#2AABB3','#1890FF','#52C41A','#FAAD14','#FF4D4F','#722ED1'];
    new Chart(document.getElementById('srDeptChart'), {
        type: 'bar',
        data: {
            labels: <?php echo json_encode($dept_labels); ?>,
            datasets: [{
                label: 'Requests',
                data: <?php echo json_encode($dept_counts); ?>,
                backgroundColor: dc.slice(0, <?php echo count($dept_labels); ?>),
                borderWidth: 0, borderRadius: 4, barThickness: 16
            }]
        },
        options: {
            indexAxis: 'y', responsive: true, maintainAspectRatio: false,
            plugins: { legend:{display:false}, tooltip:tt },
            scales: {
                x: { beginAtZero:true, grid:{color:'#F3F4F6'}, ticks:{font:cf, stepSize:1} },
                y: { grid:{display:false}, ticks:{font:cf, autoSkip:false} }
            }
        }
    });

    // ═══ Top Requested Items — HORIZONTAL bar ═══
    var topItemLabels = <?php echo json_encode($top_item_labels); ?>;
    var topItemCounts = <?php echo json_encode($top_item_counts); ?>;
    if (topItemLabels.length > 0) {
        new Chart(document.getElementById('srTopItemsChart'), {
            type: 'bar',
            data: {
                labels: topItemLabels,
                datasets: [{
                    label: 'Times Requested',
                    data: topItemCounts,
                    backgroundColor: 'rgba(24,144,255,0.75)',
                    borderColor: '#1677FF', borderWidth: 1, borderRadius: 3, barThickness: 14
                }]
            },
            options: {
                indexAxis: 'y', responsive: true, maintainAspectRatio: false,
                plugins: { legend:{display:false}, tooltip:tt },
                scales: {
                    x: { beginAtZero:true, grid:{color:'#F3F4F6'}, ticks:{font:cf} },
                    y: { grid:{display:false}, ticks:{font:{family:'Poppins',size:9}, autoSkip:false} }
                }
            }
        });
    }

    // ═══ Category Doughnut ═══
    var catLabels = <?php echo json_encode($cat_labels); ?>;
    var catCounts = <?php echo json_encode($cat_counts); ?>;
    var catColors = ['#2AABB3','#1890FF','#52C41A','#FAAD14','#FF4D4F','#722ED1','#13C2C2','#EB2F96'];
    if (catLabels.length > 0) {
        new Chart(document.getElementById('srCategoryChart'), {
            type: 'doughnut',
            data: {
                labels: catLabels,
                datasets: [{
                    data: catCounts,
                    backgroundColor: catColors.slice(0, catLabels.length),
                    borderWidth: 2, borderColor: '#fff'
                }]
            },
            options: {
                responsive: true, maintainAspectRatio: false, cutout: '55%',
                plugins: {
                    legend: { position:'right', labels:{font:{family:'Poppins',size:10}, boxWidth:12, padding:6} },
                    tooltip: tt
                }
            }
        });
    }

    // ═══ Monthly Qty Trend — Dual-axis line ═══
    var qtyLabels = <?php echo json_encode($qty_month_labels); ?>;
    var qtyVals = <?php echo json_encode($qty_month_vals); ?>;
    var qtyUnique = <?php echo json_encode($qty_unique_vals); ?>;
    if (qtyLabels.length > 0) {
        new Chart(document.getElementById('srQtyTrendChart'), {
            type: 'line',
            data: {
                labels: qtyLabels,
                datasets: [{
                    label: 'Qty Dispatched',
                    data: qtyVals,
                    borderColor: '#2AABB3', backgroundColor: 'rgba(42,171,179,0.1)',
                    borderWidth: 2, fill: true, tension: 0.3,
                    pointRadius: 4, pointBackgroundColor: '#2AABB3', yAxisID: 'y'
                },{
                    label: 'Unique Items',
                    data: qtyUnique,
                    borderColor: '#722ED1', backgroundColor: 'rgba(114,46,209,0.08)',
                    borderWidth: 2, fill: false, tension: 0.3,
                    pointRadius: 4, pointBackgroundColor: '#722ED1',
                    borderDash: [4,3], yAxisID: 'y1'
                }]
            },
            options: {
                responsive: true, maintainAspectRatio: false,
                plugins: { legend:{labels:{font:{family:'Poppins',size:10}, boxWidth:12}}, tooltip:tt },
                scales: {
                    x: { grid:{color:'#F3F4F6'}, ticks:{font:cf} },
                    y: { beginAtZero:true, position:'left', grid:{color:'#F3F4F6'}, ticks:{font:cf},
                        title:{display:true, text:'Qty', font:{family:'Poppins',size:10}, color:'#2AABB3'} },
                    y1: { beginAtZero:true, position:'right', grid:{display:false}, ticks:{font:cf},
                        title:{display:true, text:'Items', font:{family:'Poppins',size:10}, color:'#722ED1'} }
                }
            }
        });
    }
});

function toggleSRDash() {
    var d=document.getElementById('srDashboard'), t=document.getElementById('srDashToggle');
    var c=d.classList.contains('collapsed');
    if(c){d.classList.remove('collapsed');t.classList.remove('collapsed');localStorage.setItem('sr_dash_collapsed','false');}
    else{d.classList.add('collapsed');t.classList.add('collapsed');localStorage.setItem('sr_dash_collapsed','true');}
}

function switchItemTab(tab, el) {
    var tabs = el.parentElement.querySelectorAll('.sr-tab');
    for (var i=0; i<tabs.length; i++) tabs[i].classList.remove('active');
    el.classList.add('active');
    document.getElementById('srItemsAlltime').classList.remove('active');
    document.getElementById('srItemsThismonth').classList.remove('active');
    if (tab === 'alltime') { document.getElementById('srItemsAlltime').classList.add('active'); }
    else { document.getElementById('srItemsThismonth').classList.add('active'); }
}
</script>

<script src="includes/vendors/owl.carousel/dist/owl.carousel.js" type="text/javascript"></script>
</body>
</html>

<?php
include('includes/MainMenuLinksArray.php');

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

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