<?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');
include('../../includes/footer.php');

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

$filter_store = $_GET['store_id'] ?? '';
$filter_product = $_GET['product_id'] ?? '';
$filter_type = $_GET['adjustment_type'] ?? '';
$filter_date_from = $_GET['date_from'] ?? '';
$filter_date_to = $_GET['date_to'] ?? '';

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

if ($filter_store !== '') {
    $conditions[] = 'sal.store_id = ?';
    $params[] = $filter_store;
    $types .= 'i';
}
if ($filter_product !== '') {
    $conditions[] = 'sal.product_id = ?';
    $params[] = $filter_product;
    $types .= 'i';
}
if ($filter_type !== '') {
    $conditions[] = 'sal.adjustment_type = ?';
    $params[] = $filter_type;
    $types .= 's';
}
if ($filter_date_from !== '') {
    $conditions[] = 'sal.adjusted_at >= ?';
    $params[] = $filter_date_from . ' 00:00:00';
    $types .= 's';
}
if ($filter_date_to !== '') {
    $conditions[] = 'sal.adjusted_at <= ?';
    $params[] = $filter_date_to . ' 23:59:59';
    $types .= 's';
}

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

// Count total
$count_sql = "SELECT COUNT(*) as total FROM stock_adjustments sal $where";
$count_stmt = $conn->prepare($count_sql);
if ($params) $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 adjustments with joins
$sql = "SELECT sal.*, p.product_name, s.store_name, u.first_name, u.last_name 
        FROM stock_adjustments sal
        JOIN products p ON sal.product_id = p.id
        JOIN stores s ON sal.store_id = s.id
        JOIN users u ON sal.adjusted_by = u.id
        $where
        ORDER BY sal.adjustment_date 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();
$results = $stmt->get_result();
$stmt->close();

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

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Stock Adjustment Log – Digital POS</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: 1200px;
      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;
    }
    .filters select,
    .filters input[type="date"],
    .filters button {
      padding: 10px 14px;
      border-radius: 10px;
      border: none;
      background: rgba(255, 255, 255, 0.1);
      color: white;
      font-size: 14px;
    }
    .filters button {
      background: #ff6f00;
      font-weight: bold;
      cursor: pointer;
    }
    .filters button:hover {
      background: #e65c00;
    }
    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: 0.95rem;
    }
    th {
      background: rgba(255, 111, 0, 0.9);
    }
    .adjust-add { color: #4caf50; font-weight: bold; }
    .adjust-remove { color: #e53935; font-weight: bold; }
    .pagination {
      margin-top: 20px;
      text-align: center;
    }
    .pagination a {
      background: #ff6f00;
      color: white;
      padding: 8px 14px;
      margin: 2px;
      border-radius: 6px;
      text-decoration: none;
    }
    .pagination a.active {
      background: #e65c00;
      font-weight: bold;
    }
    @media (max-width: 768px) {
      .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;
      }
    }
     .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>Stock Adjustment Log</h2>

    <form method="GET" class="filters">
      <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="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="adjustment_type">
        <option value="">All Types</option>
        <option value="add" <?= $filter_type === 'add' ? 'selected' : '' ?>>Addition</option>
        <option value="remove" <?= $filter_type === 'remove' ? 'selected' : '' ?>>Removal</option>
      </select>

      <input type="date" name="date_from" value="<?= htmlspecialchars($filter_date_from) ?>" />
      <input type="date" name="date_to" value="<?= htmlspecialchars($filter_date_to) ?>" />
      <button type="submit">Filter</button>
    </form>

    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>Store</th>
          <th>Product</th>
          <th>Type</th>
          <th>Quantity</th>
          <th>Reason</th>
          <th>Adjusted By</th>
          <th>Timestamp</th>
        </tr>
      </thead>
      <tbody>
        <?php if ($results->num_rows): ?>
          <?php while ($row = $results->fetch_assoc()): ?>
            <tr>
              <td data-label="ID"><?= $row['id'] ?></td>
              <td data-label="Store"><?= htmlspecialchars($row['store_name']) ?></td>
              <td data-label="Product"><?= htmlspecialchars($row['product_name']) ?></td>
              <td data-label="Type" class="adjust-<?= $row['adjustment_type'] ?>">
                <?= ucfirst($row['adjustment_type']) ?>
              </td>
              <td data-label="Quantity"><?= $row['adjustment_qty'] ?></td>
              <td data-label="Reason"><?= htmlspecialchars($row['reason'] ?: '-') ?></td>
              <td data-label="By"><?= htmlspecialchars($row['first_name'] . ' ' . $row['last_name']) ?></td>
              <td data-label="Time"><?= date('d M Y H:i', strtotime($row['adjustment_date'])) ?></td>
            </tr>
          <?php endwhile; ?>
        <?php else: ?>
          <tr><td colspan="8" style="text-align:center;">No adjustments 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>
</body>
</html>
