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

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

include('includes/SQL_CommonFunctions.inc');
include('includes/GetPaymentMethods.php');
include('includes/GetPrice.inc');

$userid = $_SESSION['UserID'];

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

$total_items = 0; $total_qty = 0; $total_value = 0; $zero_stock = 0;
$low_stock = 0; $categories_count = 0; $suppliers_count = 0; $locations_count = 0;
$cat_data = array(); $loc_data = array(); $top_value = array(); $low_items = array(); $recent_moves = array();

if ($dc) {
    // Single KPI query
    $r = $dc->query("SELECT 
        (SELECT COUNT(*) FROM stockmaster) as total_items,
        (SELECT COUNT(DISTINCT categoryid) FROM stockmaster WHERE categoryid IS NOT NULL) as cat_cnt,
        (SELECT COUNT(DISTINCT supplier) FROM stockmaster WHERE supplier IS NOT NULL AND supplier != '') as sup_cnt,
        (SELECT COUNT(DISTINCT loccode) FROM locstock) as loc_cnt");
    if ($r) {
        $row = $r->fetch_assoc();
        $total_items = (int)$row['total_items'];
        $categories_count = (int)$row['cat_cnt'];
        $suppliers_count = (int)$row['sup_cnt'];
        $locations_count = (int)$row['loc_cnt'];
    }

    // Stock qty & value from locstock
    $r = $dc->query("SELECT 
        IFNULL(SUM(ls.quantity),0) as total_qty,
        IFNULL(SUM(ls.quantity * sm.materialcost),0) as total_value,
        SUM(CASE WHEN ls.quantity <= 0 THEN 1 ELSE 0 END) as zero_cnt,
        SUM(CASE WHEN ls.quantity > 0 AND ls.quantity <= 5 THEN 1 ELSE 0 END) as low_cnt
        FROM locstock ls 
        INNER JOIN stockmaster sm ON ls.stockid = sm.stockid");
    if ($r) {
        $row = $r->fetch_assoc();
        $total_qty = round((float)$row['total_qty']);
        $total_value = round((float)$row['total_value'], 2);
        $zero_stock = (int)$row['zero_cnt'];
        $low_stock = (int)$row['low_cnt'];
    }

    // Stock by category (top 8)
    $r = $dc->query("SELECT sc.categorydescription as cat, COUNT(*) as cnt 
        FROM stockmaster sm LEFT JOIN stockcategory sc ON sm.categoryid = sc.categoryid
        GROUP BY sm.categoryid, sc.categorydescription ORDER BY cnt DESC LIMIT 8");
    if ($r) { while ($row = $r->fetch_assoc()) { $cat_data[] = $row; } }

    // Stock qty by location (top 6)
    $r = $dc->query("SELECT l.locationname, SUM(ls.quantity) as qty
        FROM locstock ls LEFT JOIN locations l ON ls.loccode = l.loccode
        GROUP BY ls.loccode, l.locationname ORDER BY qty DESC LIMIT 6");
    if ($r) { while ($row = $r->fetch_assoc()) { $loc_data[] = $row; } }

    // Top 5 items by value
    $r = $dc->query("SELECT sm.stockid, sm.description, 
        SUM(ls.quantity) as qty, sm.materialcost,
        SUM(ls.quantity * sm.materialcost) as val
        FROM stockmaster sm INNER JOIN locstock ls ON sm.stockid = ls.stockid
        WHERE ls.quantity > 0
        GROUP BY sm.stockid, sm.description, sm.materialcost
        ORDER BY val DESC LIMIT 5");
    if ($r) { while ($row = $r->fetch_assoc()) { $top_value[] = $row; } }

    // Low stock alerts (qty between 1-5)
    $r = $dc->query("SELECT sm.stockid, sm.description, ls.quantity, l.locationname
        FROM locstock ls 
        INNER JOIN stockmaster sm ON ls.stockid = sm.stockid
        LEFT JOIN locations l ON ls.loccode = l.loccode
        WHERE ls.quantity > 0 AND ls.quantity <= 5
        ORDER BY ls.quantity ASC LIMIT 5");
    if ($r) { while ($row = $r->fetch_assoc()) { $low_items[] = $row; } }

    // Recent stock movements
    $r = $dc->query("SELECT sm.stockid, sm.description, smv.type as movetype, 
        smv.qty, smv.trandate, l.locationname
        FROM stockmoves smv 
        INNER JOIN stockmaster sm ON smv.stockid = sm.stockid
        LEFT JOIN locations l ON smv.loccode = l.loccode
        ORDER BY smv.stkmoveno DESC LIMIT 5");
    if ($r) { while ($row = $r->fetch_assoc()) { $recent_moves[] = $row; } }

    $dc->close();
}

// Chart data prep
$cat_labels = array(); $cat_counts = array();
foreach ($cat_data as $c) {
    $n = isset($c['cat']) ? $c['cat'] : 'Uncategorised';
    if (strlen($n) > 20) $n = substr($n, 0, 18) . '..';
    $cat_labels[] = $n;
    $cat_counts[] = (int)$c['cnt'];
}
$loc_labels = array(); $loc_qtys = array();
foreach ($loc_data as $l) {
    $n = isset($l['locationname']) ? $l['locationname'] : 'Unknown';
    if (strlen($n) > 20) $n = substr($n, 0, 18) . '..';
    $loc_labels[] = $n;
    $loc_qtys[] = round((float)$l['qty']);
}
?>

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

/* Banner */
.sm-banner {
    background:linear-gradient(135deg, var(--sm-darker) 0%, var(--sm-primary) 50%, #3CC0C8 100%);
    border-radius:var(--sm-radius); padding:22px 28px; margin:0 0 14px 0;
    color:#fff; position:relative; overflow:hidden;
}
.sm-banner::before { content:''; position:absolute; top:-40px; right:-40px; width:180px; height:180px; border-radius:50%; background:rgba(255,255,255,0.06); }
.sm-banner::after { content:''; position:absolute; bottom:-50px; right:100px; width:140px; height:140px; border-radius:50%; background:rgba(255,255,255,0.04); }
.sm-banner h2 { margin:0 0 3px 0; font-size:20px; font-weight:600; color:#fff; }
.sm-banner-sub { font-size:12px; opacity:0.85; margin:0; }
.sm-breadcrumb { margin-top:6px; font-size:11px; opacity:0.7; }
.sm-breadcrumb a { color:#fff; text-decoration:none; }

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

/* KPI Strip */
.sm-kpi-strip { display:grid; grid-template-columns:repeat(8,1fr); gap:10px; margin-bottom:12px; }
@media (max-width:1400px) { .sm-kpi-strip { grid-template-columns:repeat(4,1fr); } }
@media (max-width:768px) { .sm-kpi-strip { grid-template-columns:repeat(2,1fr); } }

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

.sm-kpi-ic {
    width:34px; height:34px; border-radius:8px;
    display:flex; align-items:center; justify-content:center; font-size:14px; flex-shrink:0;
}
.sm-kpi-ic.teal   { background:var(--sm-light); color:var(--sm-dark); }
.sm-kpi-ic.green  { background:#F0FFF0; color:var(--sm-success); }
.sm-kpi-ic.orange { background:#FFF8E6; color:var(--sm-warning); }
.sm-kpi-ic.red    { background:#FFF0F0; color:var(--sm-danger); }
.sm-kpi-ic.blue   { background:#E6F4FF; color:var(--sm-info); }
.sm-kpi-ic.purple { background:#F3EEFF; color:var(--sm-purple); }
.sm-kpi-ic.cyan   { background:#E6FFFB; color:var(--sm-cyan); }

.sm-kpi-val { font-size:18px; font-weight:700; color:var(--sm-text); line-height:1.1; }
.sm-kpi-lbl { font-size:9px; color:var(--sm-text-sec); text-transform:uppercase; letter-spacing:0.3px; }

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

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

/* Fixed chart container */
.sm-chart-box { height:200px; max-height:200px; overflow:hidden; position:relative; }

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

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

/* Rank items */
.sm-rank { display:flex; align-items:center; gap:8px; padding:6px 0; border-bottom:1px solid #F3F4F6; }
.sm-rank:last-child { border-bottom:none; }
.sm-rank-n {
    width:22px; height:22px; border-radius:50%; background:var(--sm-light);
    color:var(--sm-dark); display:flex; align-items:center; justify-content:center;
    font-size:10px; font-weight:700; flex-shrink:0;
}
.sm-rank-nm { flex:1; font-size:11px; color:var(--sm-text); font-weight:500; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.sm-rank-v { font-size:11px; font-weight:600; color:var(--sm-dark); white-space:nowrap; }

/* Alert rows */
.sm-alert-row {
    display:flex; align-items:center; gap:10px; padding:6px 0;
    border-bottom:1px solid #F3F4F6; font-size:11px;
}
.sm-alert-row:last-child { border-bottom:none; }
.sm-alert-dot { width:8px; height:8px; border-radius:50%; flex-shrink:0; }
.sm-alert-dot.red { background:var(--sm-danger); }
.sm-alert-dot.orange { background:var(--sm-warning); }
.sm-alert-name { flex:1; color:var(--sm-text); font-weight:500; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.sm-alert-qty { font-weight:700; color:var(--sm-danger); }
.sm-alert-loc { font-size:10px; color:var(--sm-text-sec); }

/* Loading */
.sm-load-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;
}
.sm-load-overlay.out { opacity:0; pointer-events:none; }
.sm-load-box { background:var(--sm-white); border-radius:12px; padding:30px 42px; box-shadow:0 8px 30px rgba(0,0,0,0.12); text-align:center; }
.sm-spin { width:36px; height:36px; border:3px solid #E5E7EB; border-top:3px solid var(--sm-primary); border-radius:50%; animation:sm-sp 0.8s linear infinite; margin:0 auto 12px; }
@keyframes sm-sp { to { transform:rotate(360deg); } }
.sm-load-txt { font-size:13px; color:var(--sm-text-sec); font-weight:500; }

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

/* XCRUD Overlay */
.xcrud-container { margin-top:0 !important; }
.xcrud-nav { background:var(--sm-white) !important; border-radius:8px !important; border:1px solid var(--sm-border) !important; }
table.xcrud-list { border-collapse:collapse !important; }
table.xcrud-list thead tr { background:linear-gradient(135deg, var(--sm-darker), var(--sm-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(--sm-light) !important; }
table.xcrud-list tbody td { font-family:'Poppins',sans-serif !important; font-size:11px !important; padding:8px 10px !important; color:var(--sm-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(--sm-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(--sm-primary) !important; color:#fff !important; }
</style>

<div class="sm-load-overlay" id="smLoadModal">
    <div class="sm-load-box"><div class="sm-spin"></div><div class="sm-load-txt">Loading Stock Master...</div></div>
</div>

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

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

<!-- Banner -->
<div class="sm-banner">
    <h2><i class="fas fa-warehouse" style="margin-right:8px;"></i>Stock Master</h2>
    <p class="sm-banner-sub">Manage inventory items, categories, locations, costs & stock levels</p>
    <div class="sm-breadcrumb"><a href="index.php">Home</a> &nbsp;/&nbsp; Inventory &nbsp;/&nbsp; Stock Master</div>
</div>

<!-- Toggle -->
<div class="sm-toggle" id="smToggle" onclick="toggleSMDash()">
    <i class="fas fa-chevron-down tog-i"></i><span>Dashboard Metrics</span>
</div>

<div class="sm-dash" id="smDash">

    <!-- KPI Strip — 8 across -->
    <div class="sm-kpi-strip">
        <div class="sm-kpi">
            <div class="sm-kpi-ic teal"><i class="fas fa-boxes-stacked"></i></div>
            <div><div class="sm-kpi-val"><?php echo number_format($total_items); ?></div><div class="sm-kpi-lbl">Total Items</div></div>
        </div>
        <div class="sm-kpi info">
            <div class="sm-kpi-ic blue"><i class="fas fa-cubes"></i></div>
            <div><div class="sm-kpi-val"><?php echo number_format($total_qty); ?></div><div class="sm-kpi-lbl">Total Qty</div></div>
        </div>
        <div class="sm-kpi success">
            <div class="sm-kpi-ic green"><i class="fas fa-dollar-sign"></i></div>
            <div><div class="sm-kpi-val">$<?php echo number_format($total_value,0); ?></div><div class="sm-kpi-lbl">Stock Value</div></div>
        </div>
        <div class="sm-kpi warning">
            <div class="sm-kpi-ic orange"><i class="fas fa-exclamation-triangle"></i></div>
            <div><div class="sm-kpi-val"><?php echo number_format($low_stock); ?></div><div class="sm-kpi-lbl">Low Stock</div></div>
        </div>
        <div class="sm-kpi danger">
            <div class="sm-kpi-ic red"><i class="fas fa-ban"></i></div>
            <div><div class="sm-kpi-val"><?php echo number_format($zero_stock); ?></div><div class="sm-kpi-lbl">Zero Stock</div></div>
        </div>
        <div class="sm-kpi purple">
            <div class="sm-kpi-ic purple"><i class="fas fa-tags"></i></div>
            <div><div class="sm-kpi-val"><?php echo number_format($categories_count); ?></div><div class="sm-kpi-lbl">Categories</div></div>
        </div>
        <div class="sm-kpi cyan">
            <div class="sm-kpi-ic cyan"><i class="fas fa-truck-field"></i></div>
            <div><div class="sm-kpi-val"><?php echo number_format($suppliers_count); ?></div><div class="sm-kpi-lbl">Suppliers</div></div>
        </div>
        <div class="sm-kpi">
            <div class="sm-kpi-ic teal"><i class="fas fa-map-marker-alt"></i></div>
            <div><div class="sm-kpi-val"><?php echo number_format($locations_count); ?></div><div class="sm-kpi-lbl">Locations</div></div>
        </div>
    </div>

    <!-- Row: Category Chart | Location Chart | Top Value + Alerts -->
    <div class="sm-row-3">
        <div class="sm-card">
            <div class="sm-card-t"><i class="fas fa-chart-bar"></i> Items by Category</div>
            <div class="sm-chart-box"><canvas id="smCatChart"></canvas></div>
        </div>
        <div class="sm-card">
            <div class="sm-card-t"><i class="fas fa-map-location-dot"></i> Qty by Location</div>
            <div class="sm-chart-box"><canvas id="smLocChart"></canvas></div>
        </div>
        <div class="sm-card">
            <div class="sm-card-t"><i class="fas fa-trophy"></i> Top Items by Value</div>
            <?php 
            $rk = 1;
            foreach ($top_value as $tv) {
                $desc = isset($tv['description']) ? $tv['description'] : $tv['stockid'];
                if (strlen($desc) > 28) $desc = substr($desc, 0, 26) . '..';
                $val = '$' . number_format((float)$tv['val'], 0);
                echo '<div class="sm-rank">';
                echo '<div class="sm-rank-n">' . $rk . '</div>';
                echo '<div class="sm-rank-nm" title="' . htmlspecialchars($tv['description']) . '">' . htmlspecialchars($desc) . '</div>';
                echo '<div class="sm-rank-v">' . $val . '</div>';
                echo '</div>';
                $rk++;
            }
            if (count($top_value) == 0) echo '<div style="text-align:center;color:#999;padding:10px;font-size:11px;">No data</div>';
            ?>
        </div>
    </div>

    <!-- Row: Low Stock Alerts | Recent Movements -->
    <div style="display:grid; grid-template-columns:1fr 1fr; gap:12px; margin-bottom:12px;">
        <div class="sm-card">
            <div class="sm-card-t"><i class="fas fa-triangle-exclamation" style="color:var(--sm-warning);"></i> Low Stock Alerts <span style="font-size:9px;color:var(--sm-text-sec);font-weight:400;margin-left:auto;">(qty ≤ 5)</span></div>
            <?php if (count($low_items) > 0) {
                foreach ($low_items as $li) {
                    $desc = isset($li['description']) ? $li['description'] : $li['stockid'];
                    if (strlen($desc) > 30) $desc = substr($desc, 0, 28) . '..';
                    $dotc = ((int)$li['quantity'] <= 2) ? 'red' : 'orange';
                    $loc = isset($li['locationname']) ? $li['locationname'] : '';
                    echo '<div class="sm-alert-row">';
                    echo '<div class="sm-alert-dot ' . $dotc . '"></div>';
                    echo '<div class="sm-alert-name" title="' . htmlspecialchars($li['description']) . '">' . htmlspecialchars($desc) . '</div>';
                    echo '<div class="sm-alert-qty">' . (int)$li['quantity'] . '</div>';
                    if ($loc) echo '<div class="sm-alert-loc">' . htmlspecialchars($loc) . '</div>';
                    echo '</div>';
                }
            } else {
                echo '<div style="text-align:center;color:var(--sm-success);padding:14px;font-size:11px;"><i class="fas fa-check-circle"></i> All stock levels healthy</div>';
            } ?>
        </div>
        <div class="sm-card">
            <div class="sm-card-t"><i class="fas fa-arrow-right-arrow-left"></i> Recent Stock Movements</div>
            <table class="sm-tbl">
                <thead><tr><th>Item</th><th>Type</th><th>Qty</th><th>Date</th></tr></thead>
                <tbody>
                <?php if (count($recent_moves) > 0) {
                    foreach ($recent_moves as $mv) {
                        $desc = isset($mv['description']) ? $mv['description'] : $mv['stockid'];
                        if (strlen($desc) > 22) $desc = substr($desc, 0, 20) . '..';
                        $mt = isset($mv['movetype']) ? $mv['movetype'] : '-';
                        $mq = isset($mv['qty']) ? (float)$mv['qty'] : 0;
                        $md = isset($mv['trandate']) ? $mv['trandate'] : '-';
                        // Color type badge
                        $tc = 'sm-badge-info';
                        $mtl = strtolower($mt);
                        if (strpos($mtl,'issue') !== false || $mq < 0) $tc = 'sm-badge-danger';
                        elseif (strpos($mtl,'receipt') !== false || strpos($mtl,'grn') !== false) $tc = 'sm-badge-success';
                        elseif (strpos($mtl,'adjust') !== false) $tc = 'sm-badge-warning';
                        echo '<tr>';
                        echo '<td title="' . htmlspecialchars($mv['description']) . '">' . htmlspecialchars($desc) . '</td>';
                        echo '<td><span class="sm-badge ' . $tc . '">' . htmlspecialchars($mt) . '</span></td>';
                        echo '<td style="font-weight:600;">' . number_format($mq) . '</td>';
                        echo '<td>' . htmlspecialchars($md) . '</td>';
                        echo '</tr>';
                    }
                } else {
                    echo '<tr><td colspan="4" style="text-align:center;color:#999;padding:14px;">No recent movements</td></tr>';
                } ?>
                </tbody>
            </table>
        </div>
    </div>

</div><!-- /sm-dash -->

<!-- Section Label -->
<div class="sm-sec-lbl"><i class="fas fa-table"></i> Stock Master Records</div>

<!-- ── XCRUD (100% original logic preserved) ── -->
<div class="col-sm-12" style="padding:0;">
<?php
include('xcrud/xcrud.php');
$timenow = date('Y-m-d H:i:s');
$ebusiness = Xcrud::get_instance();
$ebusiness->table('stockmaster');
$ebusiness->table_name('Stock Master Records');

$ebusiness->before_insert('add_locstock');

$ebusiness->columns('stockid,suppliers_stockid,supplier,barcode,categoryid,description,units,materialcost,average_cost',false);
$ebusiness->fields('stockid,suppliers_stockid,supplier,barcode,categoryid,description,units,materialcost,average_cost,lastupdate', false, 'Stock Item Details');
$ebusiness->label('materialcost','Cost');

$ebusiness->unset_remove();

if ($userid =='lusi' || $userid =='nisha' || $userid =='ilimo' || $userid =='schand' ||$userid =='stephanie' || $userid =='waqa'){
    $ebusiness->unset_edit();
}

$ebusiness->set_attr('categoryid',array('id'=>'catid'));
$ebusiness->pass_default('lastupdate',$timenow);
$ebusiness->pass_var('lastupdate',$timenow);
$ebusiness->disabled('lastupdate');
$ebusiness->relation('categoryid','stockcategory','categoryid','categorydescription');
$ebusiness->relation('supplier','suppliers','supplierid','suppname');
$ebusiness->relation('units','unitsofmeasure','unitname','unitname');
$ebusiness->column_pattern('stockid', '<a href="#" class="xcrud-action" data-task="view" data-primary="{stockid}">{value}</a>');
$ebusiness->set_attr('description',array('id'=>'desc'));

// Nested: Item Taxes
$stocktaxes = $ebusiness->nested_table('Item Taxes','stockid','item_tax','stockid');
$stocktaxes->relation('stockid','stockmaster','stockid','description');
$stocktaxes->relation('sales_tax','new_sales_tax','id','name');
$stocktaxes->set_attr('sale_tax',array('id'=>'salestax'));
$stocktaxes->set_attr('name',array('id'=>'name'));
$stocktaxes->set_attr('abbr',array('id'=>'abbr'));
$stocktaxes->set_attr('tax_label',array('id'=>'tax_label'));

// Nested: Stock Location/Warehouse
$stockloc = $ebusiness->nested_table('Stock Location/Warehouse','stockid','locstock','stockid');
$stockloc->relation('loccode','locations','loccode','locationname');
$stockloc->unset_add();
$stockloc->disabled('loccode');
$stockloc->unset_remove();

echo $ebusiness->render();

echo '</div>';
?>

</div><!-- /main padding -->

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

    if (localStorage.getItem('sm_dash_collapsed') === 'true') {
        document.getElementById('smDash').classList.add('collapsed');
        document.getElementById('smToggle').classList.add('collapsed');
    }

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

    // Category — horizontal bar
    new Chart(document.getElementById('smCatChart'), {
        type: 'bar',
        data: {
            labels: <?php echo json_encode($cat_labels); ?>,
            datasets: [{
                label: 'Items',
                data: <?php echo json_encode($cat_counts); ?>,
                backgroundColor: ['#2AABB3','#1890FF','#52C41A','#FAAD14','#FF4D4F','#722ED1','#13C2C2','#EB2F96'],
                borderWidth: 0,
                borderRadius: 4,
                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, stepSize:1} },
                y: { grid:{display:false}, ticks:{font:{family:'Poppins',size:10}, autoSkip:false} }
            }
        }
    });

    // Location — horizontal bar
    new Chart(document.getElementById('smLocChart'), {
        type: 'bar',
        data: {
            labels: <?php echo json_encode($loc_labels); ?>,
            datasets: [{
                label: 'Quantity',
                data: <?php echo json_encode($loc_qtys); ?>,
                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, callback:function(v){return v>=1000?(v/1000).toFixed(0)+'k':v;}} },
                y: { grid:{display:false}, ticks:{font:cf} }
            }
        }
    });
});

function toggleSMDash() {
    var d=document.getElementById('smDash'), t=document.getElementById('smToggle');
    var c=d.classList.contains('collapsed');
    if(c){d.classList.remove('collapsed');t.classList.remove('collapsed');localStorage.setItem('sm_dash_collapsed','false');}
    else{d.classList.add('collapsed');t.classList.add('collapsed');localStorage.setItem('sm_dash_collapsed','true');}
}
</script>

<!-- Original description validation JS -->
<script>
jQuery(document).ready(function($){
    $(".xcrud").on("change","#desc",function(){
        var status = $("#desc").val();
        if($.trim($('#desc').val()).length > 200 ){
            alert('It should less than 200 characters including spaces');
            $('#desc').focus();
            return false;
        }
        if($('#desc').val()=='') {
            alert('Description should not be blank');
            $('#desc').focus();
            return false;
        }
    });
});
</script>

<script type="text/javascript">
jQuery(document).on("ready xcrudafterrequest",function(){ });
</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'];
}
?>