<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header("Location: ../../index.php");
    exit();
}
$user_role = $_SESSION['role_id'];

include('../../includes/config.php');
include('../../includes/header.php');

// Audit log
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
$stmt = $conn->prepare("INSERT INTO audit_log (user_id, action, details, created_at, module, role_id, device_info) VALUES (?, ?, ?, NOW(), ?, ?, ?)");
$action = 'view_inventory';
$module = 'Inventory';
$details = json_encode(['page'=>'inventory.php','timestamp'=>date('Y-m-d H:i:s')]);
$stmt->bind_param("isssis", $_SESSION['user_id'], $action, $details, $module, $user_role, $user_agent);
$stmt->execute(); $stmt->close();

$limit = 10;
$page = max(1, (int)($_GET['page'] ?? 1));
$offset = ($page - 1) * $limit;

$filter_product = $_GET['product_id'] ?? '';
$filter_store = $_GET['store_id'] ?? '';

$conds = ["i.deleted_at IS NULL"];
$params = []; $types = '';

if ($filter_product !== '') { $conds[] = "i.product_id = ?"; $params[] = $filter_product; $types .= 'i'; }
if ($filter_store !== '') { $conds[] = "i.store_id = ?"; $params[] = $filter_store; $types .= 'i'; }

$where = $conds ? "WHERE " . implode(" AND ", $conds) : "";

// Total count
$total_stmt = $conn->prepare("SELECT COUNT(*) AS total FROM inventory i $where");
if ($params) $total_stmt->bind_param($types, ...$params);
$total_stmt->execute();
$total = $total_stmt->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total / $limit);
$total_stmt->close();

// Fetch data
$sql = "
SELECT i.*, p.product_name, s.store_name, u.username AS modified_by_user
FROM inventory i
JOIN products p ON i.product_id = p.id
JOIN stores s ON i.store_id = s.id
LEFT JOIN users u ON i.modified_by = u.id
$where
ORDER BY i.updated_at DESC
LIMIT ? OFFSET ?";
$stmt = $conn->prepare($sql);
if ($params) {
    $stmt->bind_param($types . "ii", ...array_merge($params, [$limit, $offset]));
} else {
    $stmt->bind_param("ii", $limit, $offset);
}
$stmt->execute();
$inventory = $stmt->get_result();
$stmt->close();

// Summary
$summary_sql = "
SELECT 
    COUNT(*) AS total_items,
    SUM(i.quantity) AS total_qty,
    SUM(i.quantity * i.cost_price) AS total_cost,
    SUM(i.quantity * i.selling_price) AS total_sales
FROM inventory i
$where";
$sum_stmt = $conn->prepare($summary_sql);
if ($params) $sum_stmt->bind_param($types, ...$params);
$sum_stmt->execute();
$summary = $sum_stmt->get_result()->fetch_assoc();
$sum_stmt->close();

$products = $conn->query("SELECT id, product_name FROM products ORDER BY product_name ASC");
$stores = $conn->query("SELECT id, store_name FROM stores ORDER BY store_name ASC");
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Inventory – Digital POS</title>
  <link rel="stylesheet" href="../../css/dashboard.css">
  <style>
    body, html {
        margin: 0;
        font-family: 'Segoe UI', sans-serif;
        background: url('../../images/profile.jpg') no-repeat center center fixed;
        background-size: cover;
        color: white;
    }
    .overlay {
        position: fixed;
        top: 0; left: 0;
        width: 100%; height: 100%;
        background: rgba(0,0,0,0.6);
        z-index: -1;
    }
    .content {
        margin: 100px auto 40px auto;
        max-width: 1250px;
        padding: 30px 40px;
        background: rgba(255,255,255,0.08);
        backdrop-filter: blur(15px);
        border-radius: 20px;
        box-shadow: 0 8px 32px rgba(0,0,0,0.5);
    }
    h2 {
        text-align: center;
        margin-bottom: 25px;
        font-size: 1.8rem;
    }
    .filters {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin-bottom: 20px;
        justify-content: space-between;
        align-items: center;
    }
    .filters form {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        flex-grow: 1;
    }
    select, .filters button {
        padding: 10px 14px;
        border-radius: 10px;
        border: none;
        background: rgba(255,255,255,0.2);
        color: white;
        font-size: 14px;
        cursor: pointer;
    }
    .filters button[type="submit"],
    .filters button[type="button"] {
        background: #ff6f00;
        transition: background 0.3s ease;
    }
    .filters button:hover {
        background: #e65c00;
    }
    .summary {
        display: flex;
        flex-wrap: wrap;
        gap: 15px;
        margin-bottom: 25px;
        justify-content: space-between;
    }
    .summary-box {
        flex: 1;
        padding: 16px;
        background: rgba(255,255,255,0.08);
        border-radius: 12px;
        text-align: center;
        font-size: 15px;
    }
    .summary-box strong {
        display: block;
        font-size: 18px;
        color: #ffa500;
    }
    table {
        width: 100%;
        border-collapse: collapse;
        background: rgba(0,0,0,0.3);
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 0 12px rgba(0,0,0,0.6);
    }
    th, td {
        padding: 12px 14px;
        border-bottom: 1px solid rgba(255,255,255,0.1);
        text-align: left;
        font-size: 14px;
    }
    th {
        background: rgba(255,111,0,0.9);
    }
    .actions a {
        margin-right: 12px;
        color: #ffa500;
        font-weight: bold;
        text-decoration: none;
    }
    .actions a.delete {
        color: #ff4d4d;
    }
    .pagination {
        margin-top: 20px;
        text-align: center;
    }
    .pagination a {
        padding: 6px 12px;
        margin: 2px;
        border-radius: 5px;
        background: rgba(255,255,255,0.1);
        color: white;
        text-decoration: none;
        font-weight: bold;
    }
    .pagination a.active {
        background: #ff6f00;
    }
    @media (max-width: 768px) {
        .filters, .summary {
            flex-direction: column;
        }
        table, thead, tbody, th, td, tr {
            font-size: 13px;
            display: block;
        }
        td::before {
            content: attr(data-label);
            display: block;
            font-weight: bold;
            color: #ffa500;
            margin-bottom: 5px;
        }
    }
  </style>
</head>
<body>
<div class="overlay"></div>
<div class="content">
  <h2>Inventory Management</h2>

  <div class="summary">
    <div class="summary-box"><strong><?= (int)$summary['total_items'] ?></strong>Total Items</div>
    <div class="summary-box"><strong><?= number_format($summary['total_qty'] ?? 0) ?></strong>Total Quantity</div>
    <div class="summary-box"><strong>MK <?= number_format($summary['total_cost'] ?? 0, 2) ?></strong>Total Cost</div>
    <div class="summary-box"><strong>MK <?= number_format($summary['total_sales'] ?? 0, 2) ?></strong>Total Sales</div>
  </div>

  <div class="filters">
    <form method="GET">
      <select name="product_id">
        <option value="">All Products</option>
        <?php while ($p = $products->fetch_assoc()): ?>
          <option value="<?= $p['id'] ?>" <?= $filter_product == $p['id'] ? 'selected' : '' ?>>
            <?= htmlspecialchars($p['product_name']) ?>
          </option>
        <?php endwhile; ?>
      </select>
      <select name="store_id">
        <option value="">All Stores</option>
        <?php while ($s = $stores->fetch_assoc()): ?>
          <option value="<?= $s['id'] ?>" <?= $filter_store == $s['id'] ? 'selected' : '' ?>>
            <?= htmlspecialchars($s['store_name']) ?>
          </option>
        <?php endwhile; ?>
      </select>
      <button type="submit">Filter</button>
    </form>
    <button type="button" onclick="window.location='add_inventory.php'">+ Add Inventory</button>
  </div>

  <table>
    <thead>
      <tr>
        <th>ID</th><th>Product</th><th>Store</th><th>Barcode</th>
        <th>Qty</th><th>Cost</th><th>Sell</th><th>Modified By</th><th>Modified At</th><th>Created At</th>
        <?php if ($user_role == 1 || $user_role == 2): ?><th>Actions</th><?php endif; ?>
      </tr>
    </thead>
    <tbody>
    <?php if ($inventory->num_rows): while ($row = $inventory->fetch_assoc()): ?>
      <tr>
        <td data-label="ID"><?= $row['id'] ?></td>
        <td data-label="Product"><?= htmlspecialchars($row['product_name']) ?></td>
        <td data-label="Store"><?= htmlspecialchars($row['store_name']) ?></td>
        <td data-label="Barcode"><?= htmlspecialchars($row['barcode']) ?></td>
        <td data-label="Qty"><?= $row['quantity'] ?></td>
        <td data-label="Cost"><?= number_format($row['cost_price'], 2) ?></td>
        <td data-label="Sell"><?= number_format($row['selling_price'], 2) ?></td>
        <td data-label="By"><?= htmlspecialchars($row['modified_by_user'] ?? 'N/A') ?></td>
        <td data-label="Modified"><?= $row['modified_at'] ? date('d M Y H:i', strtotime($row['modified_at'])) : 'N/A' ?></td>
        <td data-label="Created"><?= date('d M Y H:i', strtotime($row['created_at'])) ?></td>
        <?php if ($user_role == 1 || $user_role == 2): ?>
        <td data-label="Actions" class="actions">
          <a href="edit_inventory.php?id=<?= $row['id'] ?>">Edit</a>
          <a href="javascript:void(0);" class="delete" onclick="deleteInventory(<?= $row['id'] ?>)">Delete</a>
        </td>
        <?php endif; ?>
      </tr>
    <?php endwhile; else: ?>
      <tr><td colspan="<?= ($user_role <= 2) ? 11 : 10 ?>" style="text-align:center;">No inventory found.</td></tr>
    <?php endif; ?>
    </tbody>
  </table>

  <div class="pagination">
    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
      <a href="?<?= http_build_query(array_merge($_GET, ['page' => $i])) ?>" class="<?= ($i == $page) ? 'active' : '' ?>"><?= $i ?></a>
    <?php endfor; ?>
  </div>
</div>

<script>
function deleteInventory(id) {
  if (!confirm("Are you sure you want to delete this item?")) return;
  fetch('delete_inventory.php', {
    method: 'POST',
    headers: {'Content-Type':'application/x-www-form-urlencoded'},
    body: `id=${id}`
  })
  .then(res => res.json())
  .then(data => {
    alert(data.message);
    if (data.success) location.reload();
  })
  .catch(() => alert('❌ Network error.'));
}
</script>
<?php include('../../includes/footer.php'); ?>
</body>
</html>
