<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';
$username = $_SESSION['username'] ?? 'Guest';

// ==================== FETCH STORES ====================
$stores = $conn->query("SELECT * FROM stores ORDER BY store_name ASC");

// ==================== FETCH PRODUCTS ====================
$search = $_GET['search'] ?? '';
$where = '';
if($search){
    $search_safe = $conn->real_escape_string($search);
    $where = "WHERE p.name LIKE '%$search_safe%' OR p.sku LIKE '%$search_safe%'";
}
$products = $conn->query("SELECT p.*, c.name as category_name FROM products p LEFT JOIN categories c ON p.category_id=c.id $where ORDER BY p.id DESC");
$categories = $conn->query("SELECT * FROM categories ORDER BY name ASC");

// ==================== PRODUCT TOTAL STOCK ====================
$total_stock_value = 0;
$products_for_total = $conn->query("SELECT quantity, selling_price FROM products");
while($p = $products_for_total->fetch_assoc()){
    $total_stock_value += $p['quantity'] * $p['selling_price'];
}
?>

<div class="container mt-4">
      <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($username) ?></strong>!
    </div>
    <h3 class="text-center">Store & Inventory Management</h3>
    <hr>

    <!-- ==================== STORES LIST ==================== -->
    <h5>Stores</h5>
    <table class="table table-bordered table-striped" style="font-size:13px;">
        <thead class="bg-primary text-white">
            <tr>
                <th>#</th>
                <th>Store Name</th>
                <th>Location</th>
                <th>Manager</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php $i=1; while($store = $stores->fetch_assoc()): ?>
                <tr>
                    <td><?= $i ?></td>
                    <td><?= $store['store_name'] ?></td>
                    <td><?= $store['location'] ?></td>
                    <td><?= $store['manager'] ?></td>
                    <td>
                        <a href="edit_store.php?id=<?= $store['id'] ?>" class="btn btn-sm btn-primary">Edit</a>
                        <a href="stores.php?delete=<?= $store['id'] ?>" onclick="return confirm('Delete this store?')" class="btn btn-sm btn-danger">Delete</a>
                        <a href="store_inventory.php?store_id=<?= $store['id'] ?>" class="btn btn-sm btn-warning">View Inventory</a>
                    </td>
                </tr>
            <?php $i++; endwhile; ?>
        </tbody>
    </table>

    <!-- ==================== ADD NEW STORE ==================== -->
    <form method="POST" action="add_store.php" class="row g-3 mb-4">
        <div class="col-md-3"><input type="text" name="store_name" class="form-control" placeholder="Store Name" required></div>
        <div class="col-md-3"><input type="text" name="location" class="form-control" placeholder="Location"></div>
        <div class="col-md-3"><input type="text" name="manager" class="form-control" placeholder="Manager"></div>
        <div class="col-md-3">
            <button type="submit" class="btn btn-success w-100">Add Store</button>
        </div>
    </form>

    <hr>

    <!-- ==================== PRODUCT MANAGEMENT ==================== -->
    <h5>Products</h5>
    <!-- Add Product Form -->
    <form method="POST" class="row g-3 mb-4">
        <!-- SKU, Name, Category, Barcode, Prices, Qty, Min Level -->
        <!-- Copy your existing Add Product form here -->
    </form>

    <!-- ==================== SEARCH & EXPORT ==================== -->
    <!-- Copy your existing search & export block -->

    <!-- ==================== PRODUCT LIST ==================== -->
    <!-- Copy your existing Product Table -->

    <div class="mt-2 text-end">
        <strong>Total Stock Value (MK): <?= number_format($total_stock_value, 2) ?></strong>
    </div>

</div>

<script>
function checkStockAlerts() {
    fetch('check_stock.php')
        .then(response => response.json())
        .then(data => {
            data.forEach(item => {
                alert(`Low Stock Reminder!\nProduct: ${item.name}\nSKU: ${item.sku}\nQty: ${item.quantity}\nMin Level: ${item.min_level}`);
            });
        });
}
</script>

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