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

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

$manager_store_id = $_SESSION['store_id']; // Manager's assigned store

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

$filter_category = $_GET['category_id'] ?? '';

$conditions = ["i.store_id = ?"];
$params = [$manager_store_id];
$types = 'i';

if ($filter_category !== '') {
    $conditions[] = "p.category_id = ?";
    $params[] = $filter_category;
    $types .= 'i';
}

$where = 'WHERE ' . implode(' AND ', $conditions);

// Total rows
$count_sql = "SELECT COUNT(DISTINCT p.id) AS total
FROM products p
JOIN inventory i ON p.id = i.product_id
$where";
$count_stmt = $conn->prepare($count_sql);
$count_stmt->bind_param($types, ...$params);
$count_stmt->execute();
$total = $count_stmt->get_result()->fetch_assoc()['total'];
$count_stmt->close();

$total_pages = ceil($total / $limit);

// Fetch data
$sql = "SELECT 
    p.id, p.product_name, p.unit, p.cost_price, p.selling_price,
    c.category_name,
    i.quantity, i.restock_threshold,
    s.store_name
FROM products p
JOIN categories c ON p.category_id = c.id
JOIN inventory i ON p.id = i.product_id
JOIN stores s ON i.store_id = s.id
$where
ORDER BY p.product_name ASC
LIMIT ? OFFSET ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param($types . "ii", ...array_merge($params, [$limit, $offset]));
$stmt->execute();
$results = $stmt->get_result();
$stmt->close();

// Totals
$total_sql = "SELECT 
    SUM(i.quantity) AS total_qty,
    SUM(i.quantity * p.cost_price) AS total_cost,
    SUM(i.quantity * p.selling_price) AS total_sales,
    COUNT(*) AS total_items
FROM products p
JOIN inventory i ON p.id = i.product_id
$where";
$total_stmt = $conn->prepare($total_sql);
$total_stmt->bind_param($types, ...$params);
$total_stmt->execute();
$summary = $total_stmt->get_result()->fetch_assoc();
$total_stmt->close();

// Categories
$categories = $conn->query("SELECT id, category_name FROM categories ORDER BY category_name");
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Inventory Summary - Manager</title>
  <link rel="stylesheet" href="../../css/dashboard.css">
  <style>
    body, html {
      margin: 0;
      padding: 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"] {
      background: #ff6f00;
      transition: background 0.3s ease;
    }
    .filters button[type="submit"]:hover {
      background: #e65c00;
    }
    .export-btn {
      background: #4caf50;
      padding: 10px 18px;
      border-radius: 10px;
      color: white;
      border: none;
      cursor: pointer;
      transition: background 0.3s ease;
    }
    .export-btn:hover {
      background: #43a047;
    }
    .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);
    }
    .low-stock {
      color: #ffc107;
      font-weight: bold;
    }
    .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;
      }
    }
    .back-link {
      display: inline-block;
      margin-bottom: 20px;
      padding: 10px 20px;
      background: rgba(255, 111, 0, 0);
      color: white;
      font-weight: 600;
      border-radius: 8px;
      text-decoration: none;
      transition: background-color 0.3s ease;
    }
    .back-link:hover {
      background: #e65c00;
    }
  </style>
</head>
<body>
<div class="overlay"></div>
<div class="content">
  <a href="reports.php" class="back-link">&larr; Back to Reports</a>
  <h2>📊 Inventory Summary (Your Store)</h2>

  <div class="filters">
    <form method="GET">
      <select name="category_id">
        <option value="">All Categories</option>
        <?php while($c = $categories->fetch_assoc()): ?>
          <option value="<?= $c['id'] ?>" <?= ($filter_category == $c['id']) ? 'selected' : '' ?>>
            <?= htmlspecialchars($c['category_name']) ?>
          </option>
        <?php endwhile; ?>
      </select>
      <button type="submit">Filter</button>
    </form>
    <button class="export-btn" onclick="exportCSV()">Export CSV</button>
  </div>

  <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>MWK <?= number_format($summary['total_cost'] ?? 0, 2) ?></strong>Total Cost Value</div>
    <div class="summary-box"><strong>MWK <?= number_format($summary['total_sales'] ?? 0, 2) ?></strong>Total Sales Value</div>
  </div>

  <table>
    <thead>
      <tr>
        <th>Product</th>
        <th>Category</th>
        <th>Unit</th>
        <th>Quantity</th>
        <th>Restock Threshold</th>
        <th>Cost Price</th>
        <th>Selling Price</th>
      </tr>
    </thead>
    <tbody>
    <?php if ($results->num_rows): ?>
      <?php while ($row = $results->fetch_assoc()):
        $is_low_stock = ((int)$row['quantity'] <= (int)$row['restock_threshold']);
      ?>
        <tr class="<?= $is_low_stock ? 'low-stock' : '' ?>">
          <td><?= htmlspecialchars($row['product_name']) ?></td>
          <td><?= htmlspecialchars($row['category_name']) ?></td>
          <td><?= htmlspecialchars($row['unit']) ?></td>
          <td><?= (int)$row['quantity'] ?><?= $is_low_stock ? ' ⚠️' : '' ?></td>
          <td><?= (int)$row['restock_threshold'] ?></td>
          <td><?= number_format($row['cost_price'], 2) ?></td>
          <td><?= number_format($row['selling_price'], 2) ?></td>
        </tr>
      <?php endwhile; ?>
    <?php else: ?>
      <tr><td colspan="7" style="text-align:center;">No inventory data 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 exportCSV() {
  let rows = document.querySelectorAll('table tbody tr');
  if (rows.length === 0) {
    alert('No data to export.');
    return;
  }

  let headers = Array.from(document.querySelectorAll('table thead th')).map(th => `"${th.innerText.trim()}"`);
  let csvContent = headers.join(',') + '\n';

  rows.forEach(row => {
    let cols = row.querySelectorAll('td');
    let rowData = Array.from(cols).map(td => `"${td.innerText.replace(/"/g, '""')}"`);
    csvContent += rowData.join(',') + '\n';
  });

  const a = document.createElement('a');
  a.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csvContent);
  a.download = 'inventory_summary_manager.csv';
  a.click();
}
</script>
</body>
</html>
