<?php
require_once 'includes/auth.php';
require_once 'db.php';

// Redirect users without dashboard access to their first accessible module
if (!hasPermission('dashboard')) {
    header('Location: ' . getDefaultLandingUrl());
    exit;
}

/* AJAX — transaction values by period (called before any HTML) */
if (isset($_GET['txn_ajax'])) {
    $txnRole = $_SESSION['user_role'] ?? '';
    $allCo   = in_array($txnRole, ['admin', 'master_staff']);
    $coFilter_po  = $allCo ? "" : "AND company_id = $cid";
    $coFilter_si  = $allCo ? "" : "AND company_id = $cid";
    $coFilter_ret = $allCo ? "" : "AND company_id = $cid";

    $period = $_GET['period'] ?? '30';
    if ($period === 'fy') {
        $fyMonth = (int)date('n');
        $fyYear  = (int)date('Y');
        $fyStart = ($fyMonth >= 4) ? "$fyYear-04-01" : ($fyYear - 1) . "-04-01";
        $dateFilter_po  = "purchase_date >= '$fyStart'";
        $dateFilter_si  = "invoice_date  >= '$fyStart'";
        $dateFilter_ret = "return_date   >= '$fyStart'";
    } else {
        $days    = in_array((int)$period, [1, 7, 30]) ? (int)$period : 30;
        $interval = $days - 1;
        $dateFilter_po  = "purchase_date >= CURDATE() - INTERVAL $interval DAY";
        $dateFilter_si  = "invoice_date  >= CURDATE() - INTERVAL $interval DAY";
        $dateFilter_ret = "return_date   >= CURDATE() - INTERVAL $interval DAY";
    }
    $pur = $conn->query("
        SELECT IFNULL(SUM(net_amount), 0)
        FROM purchase_orders
        WHERE status = 'final' $coFilter_po AND $dateFilter_po
    ")->fetch_row()[0];
    $sal = $conn->query("
        SELECT IFNULL(SUM(net_total), 0)
        FROM sales_invoices
        WHERE status = 'final' $coFilter_si AND $dateFilter_si
    ")->fetch_row()[0];
    $pur_ret = $conn->query("
        SELECT IFNULL(SUM(net_amount), 0)
        FROM purchase_returns
        WHERE status = 'final' $coFilter_ret AND $dateFilter_ret
    ")->fetch_row()[0];
    $sal_ret = $conn->query("
        SELECT IFNULL(SUM(total_amount), 0)
        FROM sales_returns
        WHERE status = 'final' $coFilter_ret AND $dateFilter_ret
    ")->fetch_row()[0];
    header('Content-Type: application/json');
    echo json_encode(['purchases' => (float)$pur, 'sales' => (float)$sal, 'pur_returns' => (float)$pur_ret, 'sal_returns' => (float)$sal_ret]);
    exit;
}

require_once 'includes/header.php';
require_once 'includes/sidebar.php';

/* Summary Counts */
$dashRole      = $_SESSION['user_role'] ?? '';
$isAdmin       = $dashRole === 'admin';
$isAllCompanies = in_array($dashRole, ['admin', 'master_staff']);
$coFilter      = $isAllCompanies ? '' : "AND company_id = $cid";

$total_products = $conn->query("SELECT COUNT(*) FROM products WHERE status = 1 $coFilter")->fetch_row()[0];
$total_vendors  = $conn->query("SELECT COUNT(*) FROM vendors  WHERE status = 1 $coFilter")->fetch_row()[0];
$total_clients  = $conn->query("SELECT COUNT(*) FROM clients  WHERE status = 1 $coFilter")->fetch_row()[0];
$total_users    = $isAdmin ? $conn->query("SELECT COUNT(*) FROM users WHERE status = 1")->fetch_row()[0] : 0;

/* Inventory Snapshot — stock value proportional to PO net_amount (matches purchase value when no sales) */
$stockCoFilter = $isAllCompanies ? '' : "AND po.company_id = $cid";
$stock = $conn->query("
    SELECT
        IFNULL(SUM(pi.available_qty), 0) AS total_qty,
        IFNULL(SUM(
            po.net_amount * pi.available_qty / NULLIF(pt.po_qty, 0)
        ), 0) AS stock_value
    FROM purchase_items pi
    JOIN purchase_orders po ON po.id = pi.purchase_order_id
    JOIN (
        SELECT purchase_order_id, SUM(quantity) AS po_qty
        FROM purchase_items
        GROUP BY purchase_order_id
    ) pt ON pt.purchase_order_id = pi.purchase_order_id
    WHERE po.status = 'final' $stockCoFilter
")->fetch_assoc();

/* Recent Sales — last 3 days including today */
$recentCoFilter = $isAllCompanies ? '' : "AND si.company_id = $cid";
$recentCoCol    = $isAllCompanies ? ", cm.company_name" : "";
$recentCoJoin   = $isAllCompanies ? "JOIN company_master cm ON cm.id = si.company_id" : "";
$recent_sales = $conn->query("
    SELECT si.id, si.invoice_no, si.invoice_date, c.name AS customer, si.net_total, si.status
           $recentCoCol
    FROM sales_invoices si
    JOIN clients c ON c.id = si.client_id
    $recentCoJoin
    WHERE si.invoice_date >= CURDATE() - INTERVAL 2 DAY
      $recentCoFilter
    ORDER BY si.id DESC
");

/* Low Stock — only purchased products with total available qty < 10 */
$lsCoFilter = $isAllCompanies ? '' : "AND p.company_id = $cid";
$lsCoJoin   = $isAllCompanies ? "JOIN company_master cm ON cm.id = p.company_id" : "";
$lsCoCol    = $isAllCompanies ? ", cm.company_name" : "";
$low_stock_items = [];
$ls_res = $conn->query("
    SELECT p.id, p.name, p.unit, p.category
           $lsCoCol,
           SUM(pi.available_qty) AS total_qty
    FROM products p
    JOIN purchase_items pi ON pi.product_id = p.id
    $lsCoJoin
    WHERE p.status = 1 $lsCoFilter
    GROUP BY p.id, p.name, p.unit, p.category" . ($isAllCompanies ? ", cm.company_name" : "") . "
    HAVING total_qty < 10
    ORDER BY total_qty ASC
");
while ($r = $ls_res->fetch_assoc()) $low_stock_items[] = $r;

/* Distinct categories from low stock items */
$ls_categories = array_values(array_unique(array_filter(array_column($low_stock_items, 'category'))));

/* Stock Search */
$search_query  = trim($_GET['stock_search'] ?? '');
$search_result = null;
if ($search_query !== '') {
    $like = $conn->real_escape_string($search_query);
    $ssCoFilter = $isAllCompanies ? '' : "AND po.company_id = $cid";
    $ssCoCol    = $isAllCompanies ? ", cm.company_name" : "";
    $ssCoJoin   = $isAllCompanies ? "JOIN company_master cm ON cm.id = po.company_id" : "";
    $search_result = $conn->query("
        SELECT p.name AS product_name, p.unit,
               pi.batch_no, pi.mrp, pi.purchase_price, pi.selling_price,
               pi.gst_percent, pi.quantity, pi.available_qty,
               po.po_no, po.purchase_date
               $ssCoCol
        FROM purchase_items pi
        JOIN products p  ON p.id  = pi.product_id
        JOIN purchase_orders po ON po.id = pi.purchase_order_id
        $ssCoJoin
        WHERE p.name LIKE '%$like%' AND p.status = 1
          $ssCoFilter
        ORDER BY p.name, po.purchase_date DESC
    ");
}
?>

<?php if (!empty($_GET['access_denied'])): ?>
<div style="background:#fef2f2;border:1px solid #fecaca;border-radius:8px;padding:10px 16px;margin-bottom:16px;color:#991b1b;font-size:13px;">
    <i class="fas fa-lock" style="margin-right:6px;"></i>You don't have permission to access that page.
</div>
<?php endif; ?>

<h2 style="margin-bottom:20px;">Dashboard</h2>

<!-- Summary Cards -->
<div class="cards">
    <a href="<?= BASE_URL ?>/products/index.php" class="card card-link">
        <h3><?= number_format($total_products) ?></h3>
        <p><i class="fas fa-box" style="color:#2563eb;margin-right:5px;"></i> Products</p>
    </a>
    <a href="<?= BASE_URL ?>/vendors/index.php" class="card card-link">
        <h3><?= number_format($total_vendors) ?></h3>
        <p><i class="fas fa-industry" style="color:#10b981;margin-right:5px;"></i> Vendors</p>
    </a>
    <a href="<?= BASE_URL ?>/clients/index.php" class="card card-link">
        <h3><?= number_format($total_clients) ?></h3>
        <p><i class="fas fa-users" style="color:#f59e0b;margin-right:5px;"></i> Clients</p>
    </a>
    <?php if ($isAdmin): ?>
    <a href="<?= BASE_URL ?>/settings/users/index.php" class="card card-link">
        <h3><?= number_format($total_users) ?></h3>
        <p><i class="fas fa-user-shield" style="color:#06b6d4;margin-right:5px;"></i> Users</p>
    </a>
    <?php endif; ?>
</div>

<!-- Stats Row -->
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:16px;margin-bottom:24px;">

    <div class="panel">
        <div class="panel-header">
            <span class="panel-title"><i class="fas fa-warehouse" style="color:#2563eb;margin-right:8px;"></i>Inventory Snapshot</span>
        </div>
        <div class="panel-body">
            <div style="display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid #f1f5f9;">
                <span style="color:#64748b;font-size:13px;">Total Stock Qty</span>
                <span style="font-weight:700;font-size:18px;"><?= number_format($stock['total_qty']) ?></span>
            </div>
            <div style="display:flex;justify-content:space-between;align-items:center;padding:8px 0;">
                <span style="color:#64748b;font-size:13px;">Stock Value (Purchase)</span>
                <span style="font-weight:700;font-size:18px;">&#8377; <?= number_format($stock['stock_value'], 2) ?></span>
            </div>
        </div>
    </div>

    <div class="panel">
        <div class="panel-header">
            <span class="panel-title"><i class="fas fa-exchange-alt" style="color:#10b981;margin-right:8px;"></i>Transactions</span>
            <div style="display:flex;gap:4px;">
                <button class="btn btn-sm txn-btn" data-period="1">1 Day</button>
                <button class="btn btn-sm txn-btn" data-period="7">7 Days</button>
                <button class="btn btn-sm txn-btn active-period" data-period="30">1 Month</button>
                <button class="btn btn-sm txn-btn" data-period="fy">This FY</button>
            </div>
        </div>
        <div class="panel-body">
            <div style="display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid #f1f5f9;">
                <span style="color:#64748b;font-size:13px;">Purchase Value <span style="font-weight:400;font-size:11px;">(incl. tax)</span></span>
                <span id="txnPurchase" style="font-weight:700;font-size:18px;">—</span>
            </div>
            <div style="display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid #f1f5f9;">
                <span style="color:#64748b;font-size:13px;">Purchase Returns <span style="font-weight:400;font-size:11px;">(incl. tax)</span></span>
                <span id="txnPurReturn" style="font-weight:700;font-size:18px;color:#ef4444;">—</span>
            </div>
            <div style="display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid #f1f5f9;">
                <span style="color:#64748b;font-size:13px;">Sales Value <span style="font-weight:400;font-size:11px;">(incl. tax)</span></span>
                <span id="txnSales" style="font-weight:700;font-size:18px;">—</span>
            </div>
            <div style="display:flex;justify-content:space-between;align-items:center;padding:8px 0;">
                <span style="color:#64748b;font-size:13px;">Sales Returns <span style="font-weight:400;font-size:11px;">(incl. tax)</span></span>
                <span id="txnSalReturn" style="font-weight:700;font-size:18px;color:#ef4444;">—</span>
            </div>
        </div>
    </div>

</div>

<!-- Stock Search -->
<div class="panel" style="margin-bottom:24px;">
    <div class="panel-header">
        <span class="panel-title"><i class="fas fa-search" style="color:var(--primary);margin-right:8px;"></i>Stock Lookup</span>
    </div>
    <div class="panel-body" style="padding-bottom:<?= $search_result ? '0' : '16px' ?>;">
        <form method="get" style="display:flex;gap:10px;align-items:flex-end;">
            <div class="form-group" style="flex:1;max-width:400px;margin:0;">
                <input type="text" name="stock_search"
                       value="<?= htmlspecialchars($search_query) ?>"
                       placeholder="Type product name to search stock..."
                       autocomplete="off" style="width:100%;">
            </div>
            <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Search</button>
            <?php if ($search_query !== ''): ?>
            <a href="dashboard.php" class="btn btn-secondary"><i class="fas fa-times"></i> Clear</a>
            <?php endif; ?>
        </form>

        <?php if ($search_query !== ''): ?>
        <div style="margin-top:16px;overflow-x:auto;">
            <?php if ($search_result && $search_result->num_rows > 0): ?>
            <table>
                <thead>
                    <tr>
                        <th>Product</th>
                        <th>Batch</th>
                        <th>PO No</th>
                        <th>Date</th>
                        <?php if ($isAllCompanies): ?><th>Company</th><?php endif; ?>
                        <th style="text-align:right;">MRP</th>
                        <th style="text-align:right;">Purchase Price</th>
                        <th style="text-align:center;">GST%</th>
                        <th style="text-align:center;">Total Qty</th>
                        <th style="text-align:center;">Available</th>
                    </tr>
                </thead>
                <tbody>
                <?php while ($row = $search_result->fetch_assoc()): ?>
                <tr>
                    <td><strong><?= htmlspecialchars($row['product_name']) ?></strong>
                        <?php if ($row['unit']): ?><span style="font-size:11px;color:var(--text-muted);margin-left:4px;"><?= htmlspecialchars($row['unit']) ?></span><?php endif; ?>
                    </td>
                    <td style="font-size:12px;color:var(--text-secondary);"><?= htmlspecialchars($row['batch_no']) ?></td>
                    <td style="font-size:12px;"><?= htmlspecialchars($row['po_no']) ?></td>
                    <td style="font-size:12px;"><?= date('d-m-Y', strtotime($row['purchase_date'])) ?></td>
                    <?php if ($isAllCompanies): ?>
                    <td style="font-size:12px;color:var(--text-muted);"><?= htmlspecialchars($row['company_name'] ?? '') ?></td>
                    <?php endif; ?>
                    <td style="text-align:right;">&#8377; <?= number_format($row['mrp'], 2) ?></td>
                    <td style="text-align:right;">&#8377; <?= number_format($row['purchase_price'], 2) ?></td>
                    <td style="text-align:center;"><?= $row['gst_percent'] ?>%</td>
                    <td style="text-align:center;"><?= $row['quantity'] ?></td>
                    <td style="text-align:center;">
                        <span style="font-weight:700;color:<?= $row['available_qty'] < 10 ? 'var(--danger)' : 'var(--success)' ?>;">
                            <?= $row['available_qty'] ?>
                        </span>
                    </td>
                </tr>
                <?php endwhile; ?>
                </tbody>
            </table>
            <?php else: ?>
            <div style="padding:20px 0;color:var(--text-muted);font-size:13px;">
                <i class="fas fa-inbox" style="margin-right:6px;"></i>No stock found for "<strong><?= htmlspecialchars($search_query) ?></strong>".
            </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Low Stock Alert -->
<?php if (count($low_stock_items) > 0): ?>
<div class="panel" style="margin-bottom:24px;border-left:4px solid var(--danger);">
    <div class="panel-header" style="flex-wrap:wrap;gap:8px;">
        <span class="panel-title" style="color:var(--danger);">
            <i class="fas fa-exclamation-triangle" style="margin-right:8px;"></i>Low Stock Alert
            <span id="lsCount" style="background:var(--danger);color:#fff;border-radius:10px;padding:1px 8px;font-size:11px;margin-left:8px;"><?= count($low_stock_items) ?></span>
        </span>
        <div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;">
            <?php
            $ls_companies = [];
            if ($isAllCompanies) {
                foreach ($low_stock_items as $r) {
                    $cn = $r['company_name'] ?? '';
                    if ($cn && !in_array($cn, $ls_companies)) $ls_companies[] = $cn;
                }
                sort($ls_companies);
            }
            if (count($ls_companies) > 0): ?>
            <select id="lsCoFilter" style="font-size:12px;padding:3px 8px;border:1px solid var(--border);border-radius:4px;min-width:140px;">
                <option value="">All Companies</option>
                <?php foreach ($ls_companies as $cn): ?>
                <option value="<?= htmlspecialchars($cn) ?>"><?= htmlspecialchars($cn) ?></option>
                <?php endforeach; ?>
            </select>
            <?php endif; ?>
            <?php if (count($ls_categories) > 0): ?>
            <select id="lsCatFilter" style="font-size:12px;padding:3px 8px;border:1px solid var(--border);border-radius:4px;min-width:140px;">
                <option value="">All Categories</option>
                <?php foreach ($ls_categories as $cat): ?>
                <option value="<?= htmlspecialchars($cat) ?>"><?= htmlspecialchars($cat) ?></option>
                <?php endforeach; ?>
            </select>
            <?php endif; ?>
            <label style="font-size:12px;color:var(--text-muted);margin:0;">Per page:</label>
            <select id="lsPerPage" style="font-size:12px;padding:3px 6px;border:1px solid var(--border);border-radius:4px;">
                <option value="10">10</option>
                <option value="25">25</option>
            </select>
            <a href="<?= BASE_URL ?>/inventory/stocks.php" class="btn btn-sm btn-outline">View Stock</a>
        </div>
    </div>
    <div style="overflow-x:auto;">
        <table id="lowStockTable">
            <thead>
                <tr>
                    <th>Product</th>
                    <?php if ($isAllCompanies): ?><th>Company</th><?php endif; ?>
                    <th>Category</th>
                    <th>Unit</th>
                    <th style="text-align:center;">Available Qty</th>
                    <th style="text-align:center;">Status</th>
                </tr>
            </thead>
            <tbody id="lowStockBody"></tbody>
        </table>
    </div>
    <div id="lowStockPager" style="display:flex;gap:6px;align-items:center;justify-content:center;padding:12px 0;"></div>
</div>

<script>
(function() {
    const LS_ALL = <?= json_encode(array_map(function($r) use ($isAllCompanies) {
        return [
            'name'         => $r['name'],
            'unit'         => $r['unit'] ?? '',
            'category'     => $r['category'] ?? '',
            'total_qty'    => (float)$r['total_qty'],
            'company_name' => $isAllCompanies ? ($r['company_name'] ?? '') : '',
        ];
    }, $low_stock_items)) ?>;
    const PRODUCTS_URL  = '<?= BASE_URL ?>/products/index.php';
    const SHOW_COMPANY  = <?= $isAllCompanies ? 'true' : 'false' ?>;
    let lsPage = 1, lsPerPage = 10, lsCat = '', lsCo = '';

    function getFiltered() {
        return LS_ALL.filter(function(r) {
            return (!lsCat || r.category === lsCat) && (!lsCo || r.company_name === lsCo);
        });
    }

    function renderLS() {
        const data  = getFiltered();
        const total = data.length;
        const totalPages = Math.max(1, Math.ceil(total / lsPerPage));
        if (lsPage > totalPages) lsPage = totalPages;
        const start = (lsPage - 1) * lsPerPage;
        const slice = data.slice(start, start + lsPerPage);

        document.getElementById('lsCount').textContent = total;

        document.getElementById('lowStockBody').innerHTML = slice.map(function(r) {
            const color = r.total_qty === 0 ? 'var(--danger)' : 'var(--warning)';
            const badge = r.total_qty === 0
                ? '<span class="badge badge-danger">Out of Stock</span>'
                : '<span class="badge badge-warning">Low Stock</span>';
            const coCell = SHOW_COMPANY ? '<td style="font-size:12px;color:var(--text-muted);">' + (r.company_name || '—') + '</td>' : '';
            return '<tr>'
                + '<td><a href="' + PRODUCTS_URL + '" style="font-weight:600;color:var(--text-primary);text-decoration:none;">' + r.name + '</a></td>'
                + coCell
                + '<td style="font-size:12px;color:var(--text-muted);">' + (r.category || '—') + '</td>'
                + '<td style="font-size:12px;color:var(--text-muted);">' + (r.unit || '—') + '</td>'
                + '<td style="text-align:center;"><span style="font-weight:700;font-size:15px;color:' + color + ';">' + r.total_qty + '</span></td>'
                + '<td style="text-align:center;">' + badge + '</td>'
                + '</tr>';
        }).join('');

        // Pager
        const pager = document.getElementById('lowStockPager');
        if (totalPages <= 1) { pager.innerHTML = ''; return; }
        let html = '';
        html += '<button class="btn btn-sm btn-outline" onclick="lsGoPage(' + (lsPage-1) + ')"' + (lsPage<=1?' disabled':'') + '>&#8249; Prev</button>';
        let from = Math.max(1, lsPage - 3), to = Math.min(totalPages, from + 6);
        from = Math.max(1, to - 6);
        for (let p = from; p <= to; p++) {
            html += '<button class="btn btn-sm ' + (p===lsPage?'btn-primary':'btn-outline') + '" onclick="lsGoPage(' + p + ')">' + p + '</button>';
        }
        html += '<button class="btn btn-sm btn-outline" onclick="lsGoPage(' + (lsPage+1) + ')"' + (lsPage>=totalPages?' disabled':'') + '>Next &#8250;</button>';
        html += '<span style="font-size:12px;color:var(--text-muted);margin-left:6px;">' + (start+1) + '–' + Math.min(start+lsPerPage, total) + ' of ' + total + '</span>';
        pager.innerHTML = html;
    }

    window.lsGoPage = function(p) {
        const totalPages = Math.ceil(getFiltered().length / lsPerPage);
        if (p < 1 || p > totalPages) return;
        lsPage = p;
        renderLS();
    };

    var coEl  = document.getElementById('lsCoFilter');
    var catEl = document.getElementById('lsCatFilter');
    if (coEl)  coEl.addEventListener('change',  function() { lsCo  = this.value; lsPage = 1; renderLS(); });
    if (catEl) catEl.addEventListener('change', function() { lsCat = this.value; lsPage = 1; renderLS(); });
    document.getElementById('lsPerPage').addEventListener('change', function() {
        lsPerPage = parseInt(this.value); lsPage = 1; renderLS();
    });

    renderLS();
})();
</script>
<?php endif; ?>

<!-- Recent Sales -->
<div class="panel">
    <div class="panel-header">
        <span class="panel-title"><i class="fas fa-receipt" style="color:#2563eb;margin-right:8px;"></i>Recent Sales
            <span style="font-size:11px;font-weight:400;color:var(--text-muted);margin-left:8px;">(last 3 days)</span>
        </span>
        <a href="<?= BASE_URL ?>/sales/index.php" class="btn btn-sm btn-outline">View All</a>
    </div>
    <div style="overflow-x:auto;">
        <table>
            <thead>
                <tr>
                    <th>Invoice No</th>
                    <th>Date</th>
                    <th>Customer</th>
                    <?php if ($isAllCompanies): ?><th>Company</th><?php endif; ?>
                    <th style="text-align:right;">Net Total</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($recent_sales->num_rows > 0): ?>
                    <?php while ($row = $recent_sales->fetch_assoc()): ?>
                    <tr>
                        <td>
                            <a href="<?= BASE_URL ?>/sales/view.php?id=<?= $row['id'] ?>" style="font-weight:600;color:var(--primary);text-decoration:none;">
                                <?= htmlspecialchars($row['invoice_no']) ?>
                            </a>
                        </td>
                        <td><?= date('d-m-Y', strtotime($row['invoice_date'])) ?></td>
                        <td><?= htmlspecialchars($row['customer']) ?></td>
                        <?php if ($isAllCompanies): ?>
                        <td style="font-size:12px;color:var(--text-muted);"><?= htmlspecialchars($row['company_name'] ?? '') ?></td>
                        <?php endif; ?>
                        <td style="text-align:right;"><strong>&#8377; <?= number_format($row['net_total'], 2) ?></strong></td>
                        <td>
                            <?php
                            $s = strtolower($row['status']);
                            $badgeClass = $s === 'final' ? 'badge-success' : ($s === 'draft' ? 'badge-warning' : 'badge-gray');
                            ?>
                            <span class="badge <?= $badgeClass ?>"><?= ucfirst($s) ?></span>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr><td colspan="<?= $isAllCompanies ? 6 : 5 ?>" style="text-align:center;padding:24px;color:var(--text-muted);">No sales in the last 3 days.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
function fmtINR(v) { return '₹ ' + v.toLocaleString('en-IN', {minimumFractionDigits:2, maximumFractionDigits:2}); }
function loadTxn(period) {
    ['txnPurchase','txnPurReturn','txnSales','txnSalReturn'].forEach(id => document.getElementById(id).textContent = '…');
    fetch('dashboard.php?txn_ajax=1&period=' + period)
        .then(r => r.json())
        .then(d => {
            document.getElementById('txnPurchase').textContent  = fmtINR(d.purchases);
            document.getElementById('txnPurReturn').textContent = fmtINR(d.pur_returns);
            document.getElementById('txnSales').textContent     = fmtINR(d.sales);
            document.getElementById('txnSalReturn').textContent = fmtINR(d.sal_returns);
        })
        .catch(() => {
            ['txnPurchase','txnPurReturn','txnSales','txnSalReturn'].forEach(id => document.getElementById(id).textContent = '—');
        });
}

document.querySelectorAll('.txn-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        document.querySelectorAll('.txn-btn').forEach(b => b.classList.remove('active-period'));
        this.classList.add('active-period');
        loadTxn(this.dataset.period);
    });
});

// Load default (1 Month) on page load
loadTxn(30);
</script>

<style>
.card-link {
    text-decoration: none;
    color: inherit;
    display: block;
    transition: transform 0.15s, box-shadow 0.15s;
}
.card-link:hover {
    transform: translateY(-3px);
    box-shadow: 0 6px 20px rgba(0,0,0,.10);
}
.txn-btn {
    background: var(--bg-light);
    border: 1px solid var(--border);
    color: var(--text-secondary);
    padding: 3px 10px;
    border-radius: 4px;
    font-size: 12px;
    cursor: pointer;
    transition: all 0.15s;
}
.txn-btn:hover { border-color: var(--primary); color: var(--primary); }
.txn-btn.active-period {
    background: var(--primary);
    border-color: var(--primary);
    color: #fff;
}
</style>

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