<?php
require_once '../includes/auth.php';
requirePermission('inventory', 'view');
require_once '../db.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

$userRole = $_SESSION['user_role'] ?? '';

$filterCo = $cid;
$companies = null;
if (in_array($userRole, ['admin', 'master_staff'])) {
    $filterCo  = isset($_GET['co']) ? (int)$_GET['co'] : 0;
    $companies = $conn->query("SELECT id, company_name FROM company_master ORDER BY company_name");
}
?>

<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<style>
#stockTable td, #stockTable th { padding: 4px 8px; font-size: 12px; white-space: nowrap; }
#stockTable th { font-size: 11px; text-transform: uppercase; letter-spacing: 0.03em; }
.dataTables_wrapper .dataTables_length select,
.dataTables_wrapper .dataTables_filter input { font-size: 12px; }
.dataTables_scrollHeadInner thead th { background: #f1f5f9 !important; }
</style>

<div class="page-header">
    <h2><i class="fas fa-warehouse" style="color:var(--primary);margin-right:8px;"></i>Stocks Inventory</h2>
    <div style="display:flex;gap:8px;">
        <button id="exportExcelBtn" class="btn btn-success btn-sm"><i class="fas fa-file-excel"></i> Excel</button>
        <button id="exportPdfBtn"   class="btn btn-danger  btn-sm"><i class="fas fa-file-pdf"></i> PDF</button>
    </div>
</div>

<!-- Controls -->
<div class="panel" style="margin-bottom:14px;">
    <div class="panel-body" style="padding:14px 16px;">
        <div style="display:flex;flex-wrap:wrap;gap:20px;align-items:center;">

            <?php if ($companies): ?>
            <form method="get" style="display:flex;align-items:center;gap:8px;margin:0;">
                <label style="font-size:13px;font-weight:600;color:var(--text-secondary);margin:0;">Company:</label>
                <select name="co" onchange="this.form.submit()" style="font-size:13px;padding:5px 10px;border:1px solid var(--border);border-radius:6px;">
                    <option value="0" <?= $filterCo == 0 ? 'selected' : '' ?>>All Companies</option>
                    <?php while ($co = $companies->fetch_assoc()): ?>
                    <option value="<?= $co['id'] ?>" <?= $filterCo == $co['id'] ? 'selected' : '' ?>>
                        <?= htmlspecialchars($co['company_name']) ?>
                    </option>
                    <?php endwhile; ?>
                </select>
                <?php if ($filterCo > 0): ?>
                <a href="stocks.php" class="btn btn-secondary btn-sm">Clear</a>
                <?php endif; ?>
            </form>
            <div style="width:1px;height:24px;background:var(--border);"></div>
            <?php endif; ?>

            <label style="display:flex;align-items:center;gap:8px;font-size:13px;font-weight:600;color:var(--text-primary);cursor:pointer;text-transform:none;letter-spacing:0;margin:0;">
                <input type="checkbox" id="batchToggle" style="width:auto;accent-color:var(--primary);">
                Show Batch-wise Stock
            </label>
            <div style="width:1px;height:24px;background:var(--border);"></div>
            <div class="col-filter-box" style="border:none;padding:0;margin:0;background:transparent;gap:6px;">
                <span class="col-filter-title">Columns:</span>
                <label><input type="checkbox" class="colToggle" data-col="0" checked> Product</label>
                <label><input type="checkbox" class="colToggle" data-col="1" checked> Brand</label>
                <label><input type="checkbox" class="colToggle" data-col="2" checked> Category</label>
                <label><input type="checkbox" class="colToggle" data-col="3"> Batch No</label>
                <label><input type="checkbox" class="colToggle" data-col="4" checked> Vendor</label>
                <label><input type="checkbox" class="colToggle" data-col="5"> Purchase Date</label>
                <label><input type="checkbox" class="colToggle" data-col="6" checked> MRP</label>
                <label><input type="checkbox" class="colToggle" data-col="7" checked> Purchase Price</label>
                <label><input type="checkbox" class="colToggle" data-col="8" checked> Selling Price</label>
                <label><input type="checkbox" class="colToggle" data-col="9" checked> Total Qty</label>
                <label><input type="checkbox" class="colToggle" data-col="10" checked> Avail Qty</label>
                <label><input type="checkbox" class="colToggle" data-col="11"> GST %</label>
                <label><input type="checkbox" class="colToggle" data-col="12"> Expiry</label>
            </div>
        </div>
    </div>
</div>

<div class="panel">
    <div style="overflow-x:auto;padding:0;">
        <table id="stockTable" class="list-table display" style="width:100%">
            <thead>
                <tr>
                    <th>Product</th><th>Brand</th><th>Category</th><th>Batch No</th>
                    <th>Vendor</th><th>Purchase Date</th><th>MRP</th><th>Purchase Price</th>
                    <th>Selling Price</th><th>Total Qty</th><th>Available Qty</th>
                    <th>GST %</th><th>Expiry</th>
                </tr>
            </thead>
        </table>
    </div>
</div>

<script>
let stockTable;
const filterCo = <?= (int)$filterCo ?>;

function getSelectedColumns() {
    let cols = [];
    $('.colToggle:checked').each(function() { cols.push($(this).data('col')); });
    return cols.join(",");
}

$('#exportExcelBtn').on('click', function() {
    const search = encodeURIComponent(stockTable ? stockTable.search() : '');
    window.open(`export_excel.php?search=${search}&cols=${encodeURIComponent(getSelectedColumns())}&batch=${document.getElementById('batchToggle').checked ? 1 : 0}&co=${filterCo}`, "_blank");
});
$('#exportPdfBtn').on('click', function() {
    const search = encodeURIComponent(stockTable ? stockTable.search() : '');
    window.open(`export_pdf.php?search=${search}&cols=${encodeURIComponent(getSelectedColumns())}&batch=${document.getElementById('batchToggle').checked ? 1 : 0}&co=${filterCo}`, "_blank");
});

function initTable(batchWise = false) {
    if ($.fn.DataTable.isDataTable('#stockTable')) {
        stockTable.destroy();
        $('#stockTable').removeClass('dataTable').html(`<thead><tr>
            <th>Product</th><th>Brand</th><th>Category</th><th>Batch No</th>
            <th>Vendor</th><th>Purchase Date</th><th>MRP</th><th>Purchase Price</th>
            <th>Selling Price</th><th>Total Qty</th><th>Available Qty</th><th>GST %</th><th>Expiry</th>
        </tr></thead>`);
    }
    stockTable = $('#stockTable').DataTable({
        processing: true, serverSide: true, pageLength: 25,
        lengthMenu: [[10, 25, 50, 100, 500], ['10', '25', '50', '100', '500']],
        scrollY: "calc(100vh - 390px)",
        scrollX: true,
        scrollCollapse: true,
        ajax: {
            url: batchWise ? "stocks_batch_ajax.php" : "stocks_ajax.php",
            type: "POST",
            data: function(d) { d.co = filterCo; return d; }
        },
        columns: [
            {data:"product_name"},{data:"brand"},{data:"category"},{data:"batch_no"},
            {data:"vendor_name"},{data:"purchase_date"},{data:"mrp"},{data:"purchase_price"},
            {data:"selling_price"},{data:"quantity"},{data:"available_qty"},
            {data:"gst_percent"},{data:"expiry_date"}
        ],
        order: [[0, "asc"]],
        drawCallback: function() { applyColumnVisibility(); }
    });
    applyColumnVisibility();
}

function applyColumnVisibility() {
    $('.colToggle').each(function() {
        stockTable.column($(this).data('col')).visible($(this).is(':checked'));
    });
}

$('#batchToggle').on('change', function() {
    initTable(this.checked);
    $('input[data-col="3"]').prop('checked', this.checked);
    $('input[data-col="5"]').prop('checked', this.checked);
    $('input[data-col="12"]').prop('checked', this.checked);
});

$(document).on('change', '.colToggle', function() { applyColumnVisibility(); });

initTable(false);
$('input[data-col="3"]').prop('checked', false);
$('input[data-col="5"]').prop('checked', false);
$('input[data-col="12"]').prop('checked', false);
</script>

<?php require_once '../includes/footer.php'; ?>
