<?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'];

// Pagination settings
$rowsPerPage = 20;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? intval($_GET['page']) : 1;
$start = ($page - 1) * $rowsPerPage;

// Count total batches
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM product_batches WHERE shop_id = ? AND is_active = 1");
$countStmt->execute([$current_shop]);
$totalBatches = $countStmt->fetchColumn();
$totalPages = ceil($totalBatches / $rowsPerPage);

// Fetch batches for current page
$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
    LIMIT $start, $rowsPerPage
");
$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">

        <div class="d-flex justify-content-between align-items-center mb-4">
            <h3 class="text-success">Product Batches</h3>
            <div>
                <a href="add_batch.php" class="btn btn-primary btn-sm">+ Add New Batch</a>
                <button class="btn btn-info btn-sm" data-toggle="modal" data-target="#printModal">Print Options</button>
            </div>
        </div>

        <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 class="no-print"><input type="checkbox" id="selectAll"></th>
                        <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 class="no-print">Actions</th>
                    </tr>
                </thead>

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

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

                        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 class="no-print"><input type="checkbox" class="selectRow"></td>
                        <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><?= $expiry ? htmlspecialchars($expiry) : 'N/A' ?></td>
                        <td><?= $status ?></td>
                        <td class="no-print">
                           <!-- <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>

        <!-- Pagination -->
        <nav class="mt-3">
            <ul class="pagination">
                <?php for($p=1; $p<=$totalPages; $p++): ?>
                    <li class="page-item <?= $p==$page?'active':'' ?>">
                        <a class="page-link" href="?page=<?= $p ?>"><?= $p ?></a>
                    </li>
                <?php endfor; ?>
            </ul>
        </nav>
    </div>
</div>

<!-- Print Modal -->
<div class="modal fade" id="printModal" tabindex="-1" role="dialog" aria-labelledby="printModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title text-success" id="printModalLabel">Print Options</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p>Select what you want to print:</p>
        <button class="btn btn-success btn-block mb-2" onclick="printSelected(); $('#printModal').modal('hide');">Print Selected</button>
        <button class="btn btn-info btn-block" onclick="printAll(); $('#printModal').modal('hide');">Print All on Page</button>
      </div>
    </div>
  </div>
</div>

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

<script>
document.getElementById('searchBox').addEventListener('keyup', function() {
    let filter = this.value.toLowerCase();
    document.querySelectorAll("#batchTable tbody tr").forEach(row => {
        row.style.display = row.innerText.toLowerCase().includes(filter) ? "" : "none";
    });
});

// Select all checkbox
document.getElementById('selectAll').addEventListener('change', function() {
    let checked = this.checked;
    document.querySelectorAll('.selectRow').forEach(cb => cb.checked = checked);
});

// Print selected rows
function printSelected() {
    let selectedRows = document.querySelectorAll('.selectRow:checked');
    if (!selectedRows.length) return alert("No rows selected to print.");

    let tableClone = document.getElementById('batchTable').cloneNode(true);
    Array.from(tableClone.tBodies[0].rows).forEach((row, i) => {
        if (!selectedRows[i].checked) row.remove();
    });

    let newWin = window.open('', '', 'width=1000,height=600');
    newWin.document.write('<html><head><title>Print Batches</title>');
    newWin.document.write('<link rel="stylesheet" href="../assets/css/bootstrap.min.css">');
    newWin.document.write('<style> .no-print{display:none;} </style></head><body>');
    newWin.document.write(tableClone.outerHTML);
    newWin.document.write('</body></html>');
    newWin.document.close();
    newWin.print();
}

// Print all rows on page
function printAll() {
    let tableClone = document.getElementById('batchTable').cloneNode(true);
    let newWin = window.open('', '', 'width=1000,height=600');
    newWin.document.write('<html><head><title>Print Batches</title>');
    newWin.document.write('<link rel="stylesheet" href="../assets/css/bootstrap.min.css">');
    newWin.document.write('<style> .no-print{display:none;} </style></head><body>');
    newWin.document.write(tableClone.outerHTML);
    newWin.document.write('</body></html>');
    newWin.document.close();
    newWin.print();
}
</script>