<?php
session_start();
require_once '../assets/db_connect.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

// Ensure session has shop assigned
if (!isset($_SESSION['user']['id']) || !isset($_SESSION['user']['shop_id'])) {
    header("Location: ../auth/login.php");
    exit();
}

$current_shop = $_SESSION['user']['shop_id'];

// Fetch active batches for this shop
$stmt = $pdo->prepare("
    SELECT pb.*, p.name AS product_name, s.name AS supplier_name
    FROM product_batches pb
    LEFT JOIN products p ON pb.product_id = p.id
    LEFT JOIN suppliers s ON pb.supplier_id = s.id
    WHERE pb.shop_id = ? AND pb.is_active = 1
    ORDER BY pb.id DESC
");
$stmt->execute([$current_shop]);
$batches = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="col-md-10 ml-sm-auto px-4 py-4">
    <div class="container-fluid">

        <!-- Message -->
        <?php if (isset($_SESSION['message'])): ?>
            <div class="alert alert-<?= $_SESSION['message']['status'] === 'success' ? 'success' : 'danger' ?> mb-3">
                <?= htmlspecialchars($_SESSION['message']['text']) ?>
            </div>
            <?php unset($_SESSION['message']); ?>
        <?php endif; ?>

        <div class="d-flex justify-content-between align-items-center mb-4">
            <h3 class="text-success">Product Batches</h3>
            <a href="add_batch.php" class="btn btn-primary btn-sm">
                ? Add New Batch
            </a>
        </div>

        <div class="card shadow-sm p-3">

            <input type="text" id="searchBox" class="form-control mb-3"
                   placeholder="Search product, batch no, supplier...">

            <div class="table-responsive">
                <table class="table table-bordered table-striped table-sm" id="batchTable">
                    <thead class="thead-dark">
                        <tr>
                            <th>#</th>
                            <th>Product</th>
                            <th>Batch No</th>
                            <th>Qty</th>
                            <th>Cost Price</th>
                            <th>Sell Price</th>
                            <th>Supplier</th>
                            <th>Expiry</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>

                    <tbody>
                        <?php
                        $i = 1;
                        $today = date("Y-m-d");

                        foreach ($batches as $b):
                            $expiry = $b['expiry_date'] ?? null;

                            // EXPIRY STATUS
                            if (!$expiry) {
                                $status = "<span class='badge badge-secondary'>No Date</span>";
                            } elseif ($expiry < $today) {
                                $status = "<span class='badge badge-danger'>Expired</span>";
                            } elseif ($expiry <= date("Y-m-d", strtotime("+90 days"))) {
                                $status = "<span class='badge badge-warning'>Near Expiry</span>";
                            } else {
                                $status = "<span class='badge badge-success'>Good</span>";
                            }
                        ?>

                        <tr>
                            <td><?= $i++ ?></td>
                            <td><?= htmlspecialchars($b['product_name']) ?></td>
                            <td><?= htmlspecialchars($b['batch_no']) ?></td>
                            <td><?= number_format($b['qty']) ?></td>
                            <td><?= number_format($b['cost_price'], 2) ?></td>
                            <td><?= number_format($b['sell_price'], 2) ?></td>
                            <td><?= htmlspecialchars($b['supplier_name']) ?></td>
                            <td><?= htmlspecialchars($expiry) ?></td>
                            <td><?= $status ?></td>

                            <td>
                                <a href="edit_batch.php?id=<?= $b['id'] ?>" class="btn btn-warning btn-sm">
                                    ?? Edit
                                </a>
                                <a href="delete_batch.php?id=<?= $b['id'] ?>"
                                   class="btn btn-danger btn-sm"
                                   onclick="return confirm('Are you sure you want to delete this batch?');">
                                    ? Delete
                                </a>
                            </td>
                        </tr>

                        <?php endforeach; ?>
                    </tbody>

                </table>
            </div>

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

<script>
document.getElementById('searchBox').addEventListener('keyup', function() {
    let filter = this.value.toLowerCase();
    let rows = document.querySelectorAll("#batchTable tbody tr");

    rows.forEach(row => {
        row.style.display = row.innerText.toLowerCase().includes(filter) ? "" : "none";
    });
});
</script>

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