<?php
session_start();
if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 1) {
    header("Location: ../../index.php");
    exit();
}
include('../../includes/config.php');
include('../../includes/header.php');

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

$filter_product = $_GET['product_id'] ?? '';
$filter_store = $_GET['store_id'] ?? '';
$filter_supplier = $_GET['supplier_id'] ?? '';
$start_date = $_GET['start_date'] ?? '';
$end_date = $_GET['end_date'] ?? '';

$conds = [];
$params = [];
$types = '';

if ($filter_product !== '') { $conds[] = "se.product_id = ?"; $params[] = $filter_product; $types .= 'i'; }
if ($filter_store !== '') { $conds[] = "se.store_id = ?"; $params[] = $filter_store; $types .= 'i'; }
if ($filter_supplier !== '') { $conds[] = "se.supplier_id = ?"; $params[] = $filter_supplier; $types .= 'i'; }
if ($start_date && $end_date) { $conds[] = "se.purchase_date BETWEEN ? AND ?"; $params[] = $start_date; $params[] = $end_date; $types .= 'ss'; }

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

// Count total
$countStmt = $conn->prepare("SELECT COUNT(*) AS total FROM stock_entries se $where");
if ($params) $countStmt->bind_param($types, ...$params);
$countStmt->execute();
$total = $countStmt->get_result()->fetch_assoc()['total'];
$countStmt->close();
$totalPages = ceil($total / $limit);

// Summary
$sumStmt = $conn->prepare("SELECT SUM(se.quantity) as total_qty, SUM(se.quantity * se.cost_price) as total_cost FROM stock_entries se $where");
if ($params) $sumStmt->bind_param($types, ...$params);
$sumStmt->execute();
$summary = $sumStmt->get_result()->fetch_assoc();
$sumStmt->close();

// Main data
$sql = "
  SELECT se.*, p.product_name, s.store_name, sup.supplier_name,
         u.username AS added_by_user, u2.username AS updated_by_user
  FROM stock_entries se
  JOIN products p ON se.product_id = p.id
  JOIN stores s ON se.store_id = s.id
  LEFT JOIN suppliers sup ON se.supplier_id = sup.id
  JOIN users u ON se.added_by = u.id
  LEFT JOIN users u2 ON se.updated_by = u2.id
  $where
  ORDER BY se.created_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();
$entries = $stmt->get_result();
$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");
$suppliers = $conn->query("SELECT id, supplier_name FROM suppliers ORDER BY supplier_name ASC");
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Stock Entries - 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;
    }
    .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;
    }
    .filters {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        gap: 10px;
        margin-bottom: 20px;
        align-items: center;
    }
    .filters form {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        flex-grow: 1;
    }
    select, input[type="date"], .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"] {
        background: #ff6f00;
    }
    .filters button[type="submit"]:hover {
        background: #e65c00;
    }
    .filters .export {
        padding: 10px 18px;
        border-radius: 10px;
        color: #ffa500;
        border: 1px solid #ffa500;
        background: transparent;
        text-decoration: none;
        transition: 0.3s ease;
    }
    .filters .export:hover {
        background: #ffa500;
        color: black;
    }
    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;
        cursor: pointer;
    }
    .actions a.delete {
        color: #ff4d4d;
    }
    .actions a:last-child {
        margin-right: 0;
    }
    .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) {
        .summary, .filters {
            flex-direction: column;
        }
        table, thead, tbody, th, td, tr {
            display: block;
            font-size: 13px;
        }
        td::before {
            content: attr(data-label);
            display: block;
            font-weight: bold;
            color: #ffa500;
            margin-bottom: 5px;
        }
        .actions {
            flex-direction: column;
        }
        .actions a {
            margin: 5px 0;
        }
    }
  </style>
</head>
<body>
<div class="overlay"></div>
<div class="content">
  <h2>Stock Entries</h2>

  <div class="summary">
    <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>

  <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>
      <select name="supplier_id">
        <option value="">All Suppliers</option>
        <?php while($sup=$suppliers->fetch_assoc()): ?>
          <option value="<?= $sup['id']?>" <?= $filter_supplier==$sup['id']?'selected':''?>><?= htmlspecialchars($sup['supplier_name'])?></option>
        <?php endwhile; ?>
      </select>
      <input type="date" name="start_date" value="<?= htmlspecialchars($start_date) ?>">
      <input type="date" name="end_date" value="<?= htmlspecialchars($end_date) ?>">
      <button type="submit">Filter</button>
    </form>
    <a href="export_stock.php?<?= http_build_query($_GET) ?>&type=csv" class="export">Export CSV</a>
  </div>

  <table>
    <thead>
      <tr>
        <th>ID</th><th>Product</th><th>Supplier</th><th>Store</th><th>Qty</th><th>Cost</th>
        <th>Purchase Date</th><th>Remarks</th><th>Added By</th><th>Updated By</th>
        <th>Created</th><th>Updated</th><th>Actions</th>
      </tr>
    </thead>
    <tbody>
    <?php if ($entries->num_rows): while ($r = $entries->fetch_assoc()): ?>
      <tr>
        <td data-label="ID"><?= $r['id'] ?></td>
        <td data-label="Product"><?= htmlspecialchars($r['product_name']) ?></td>
        <td data-label="Supplier"><?= htmlspecialchars($r['supplier_name'] ?: '-') ?></td>
        <td data-label="Store"><?= htmlspecialchars($r['store_name']) ?></td>
        <td data-label="Qty"><?= $r['quantity'] ?></td>
        <td data-label="Cost">MK<?= number_format($r['cost_price'], 2) ?></td>
        <td data-label="Purchase Date"><?= $r['purchase_date'] ?></td>
        <td data-label="Remarks"><?= htmlspecialchars($r['remarks']) ?></td>
        <td data-label="Added By"><?= htmlspecialchars($r['added_by_user']) ?></td>
        <td data-label="Updated By"><?= htmlspecialchars($r['updated_by_user'] ?: '-') ?></td>
        <td data-label="Created"><?= date('d M Y H:i', strtotime($r['created_at'])) ?></td>
        <td data-label="Updated"><?= $r['updated_at'] ? date('d M Y H:i', strtotime($r['updated_at'])) : '-' ?></td>
        <td data-label="Actions" class="actions">
          <a href="edit_stock_entry.php?id=<?= $r['id'] ?>" class="edit">Edit</a>
          <a href="#" class="delete" onclick="deleteEntry(<?= $r['id'] ?>); return false;">Delete</a>
        </td>
      </tr>
    <?php endwhile; else: ?>
      <tr><td colspan="13" style="text-align:center;">No stock entries found.</td></tr>
    <?php endif; ?>
    </tbody>
  </table>

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

<script>
function deleteEntry(id) {
  if (!confirm("Delete this stock entry?")) return;
  fetch('delete_stock_entry.php', {
    method: 'POST',
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    body: `id=${id}`
  })
  .then(r => r.json())
  .then(j => {
    alert(j.message);
    if (j.success) location.reload();
  })
  .catch(() => alert("❌ Network error."));
}
</script>

<?php include('../../includes/footer.php'); ?>
</body>
</html>
