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

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

$user_role = $_SESSION['role_id'];
$user_store_id = $_SESSION['store_id'] ?? null;

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

$filter_from_store = $_GET['from_store'] ?? '';
$filter_to_store = $_GET['to_store'] ?? '';
$filter_product = $_GET['product_id'] ?? '';
$filter_start_date = $_GET['start_date'] ?? '';
$filter_end_date = $_GET['end_date'] ?? '';

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

// Manager restrictions: force store filters, disable filter inputs
if ($user_role == 2) {
    $conditions[] = "(st.from_store_id = ? OR st.to_store_id = ?)";
    $params[] = $user_store_id;
    $params[] = $user_store_id;
    $types .= 'ii';
} else {
    // Admin filters
    if ($filter_from_store !== '') {
        $conditions[] = "st.from_store_id = ?";
        $params[] = $filter_from_store;
        $types .= 'i';
    }
    if ($filter_to_store !== '') {
        $conditions[] = "st.to_store_id = ?";
        $params[] = $filter_to_store;
        $types .= 'i';
    }
}

if ($filter_product !== '') {
    $conditions[] = "st.product_id = ?";
    $params[] = $filter_product;
    $types .= 'i';
}
if ($filter_start_date !== '') {
    $conditions[] = "st.transfer_date >= ?";
    $params[] = $filter_start_date . ' 00:00:00';
    $types .= 's';
}
if ($filter_end_date !== '') {
    $conditions[] = "st.transfer_date <= ?";
    $params[] = $filter_end_date . ' 23:59:59';
    $types .= 's';
}

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

// Total count query
$count_sql = "SELECT COUNT(*) as total FROM stock_transfer_log st $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);

// Main data query
$sql = "
SELECT 
    st.*, 
    p.product_name, 
    fs.store_name AS from_store_name, 
    ts.store_name AS to_store_name,
    u.username AS transferred_by
FROM stock_transfer_log st
LEFT JOIN products p ON st.product_id = p.id
LEFT JOIN stores fs ON st.from_store_id = fs.id
LEFT JOIN stores ts ON st.to_store_id = ts.id
LEFT JOIN users u ON st.transferred_by = u.id
$where
ORDER BY st.transfer_date DESC
LIMIT ? OFFSET ?
";

$stmt = $conn->prepare($sql);
$bind_types = $params ? $types . 'ii' : 'ii';
$bind_values = array_merge($params, [$limit, $offset]);
$stmt->bind_param($bind_types, ...$bind_values);
$stmt->execute();
$transfers = $stmt->get_result();
$stmt->close();

// Dropdown data
$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 Transfer Log – Digital POS</title>
  <link rel="stylesheet" href="../../css/dashboard.css" />
  <style>
    /* Your styles unchanged */
    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;
      min-height: 100vh;
      overflow-x: hidden;
    }
    .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;
      padding: 30px 40px;
      max-width: 1200px;
      backdrop-filter: blur(15px);
      background: rgba(255, 255, 255, 0.08);
      border-radius: 20px;
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
    }
    h2 {
      text-align: center;
      font-size: 32px;
      font-weight: 700;
      margin-bottom: 25px;
      color: white;
    }
    .filters {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
    }
    .filters select, .filters input[type="date"] {
      padding: 8px 12px;
      border-radius: 8px;
      border: none;
      background: rgba(255,255,255,0.2);
      color: white;
      font-size: 14px;
    }
    .filters button, .export-btn {
      background: #ff6f00;
      color: white;
      padding: 10px 16px;
      border: none;
      border-radius: 8px;
      cursor: pointer;
      font-weight: bold;
    }
    .export-btn {
      background: #00b894;
      margin-left: auto;
    }
    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: 14px 16px;
      border-bottom: 1px solid rgba(255,255,255,0.1);
      text-align: left;
      vertical-align: middle;
      font-size: 0.95rem;
    }
    th {
      background: rgba(255,111,0,0.9);
      color: white;
      font-weight: 700;
      text-transform: uppercase;
    }
    .pagination {
      margin-top: 20px;
      text-align: center;
    }
    .pagination a {
      background: #ff6f00;
      border: none;
      color: white;
      padding: 8px 14px;
      margin: 2px;
      border-radius: 6px;
      text-decoration: none;
    }
    .pagination a.active {
      background: #e65c00;
      font-weight: bold;
    }
    .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;
    }
    @media (max-width: 768px) {
      .filters {
        flex-direction: column;
        align-items: flex-start;
      }
      table, thead, tbody, th, td, tr {
        display: block;
        font-size: 13px;
      }
      td::before {
        content: attr(data-label);
        display: block;
        font-weight: bold;
        color: #ffa500;
      }
    }
  </style>
</head>
<body>
<div class="overlay"></div>
<div class="content">
  <a href="reports.php" class="back-link">&larr; Back to Reports</a>

  <h2>Stock Transfer Log</h2>

  <div class="filters">
    <form method="GET" style="flex-grow:1; display:flex; flex-wrap:wrap; gap:10px; align-items:center;">
      <?php if ($user_role == 1): ?>
        <select name="from_store">
          <option value="">From Store (All)</option>
          <?php while($s = $stores->fetch_assoc()): ?>
            <option value="<?= $s['id'] ?>" <?= $filter_from_store == $s['id'] ? 'selected' : '' ?>>
              <?= htmlspecialchars($s['store_name']) ?>
            </option>
          <?php endwhile; ?>
        </select>

        <?php $stores->data_seek(0); ?>
        <select name="to_store">
          <option value="">To Store (All)</option>
          <?php while($s = $stores->fetch_assoc()): ?>
            <option value="<?= $s['id'] ?>" <?= $filter_to_store == $s['id'] ? 'selected' : '' ?>>
              <?= htmlspecialchars($s['store_name']) ?>
            </option>
          <?php endwhile; ?>
        </select>
      <?php else: ?>
        <!-- Manager fixed filters -->
        <input type="hidden" name="from_store" value="<?= $user_store_id ?>">
        <input type="hidden" name="to_store" value="<?= $user_store_id ?>">
        <div style="padding: 10px; font-weight: 600; color: #ff6f00;">
          Showing transfers related to your store only.
        </div>
      <?php endif; ?>

      <select name="product_id">
        <option value="">Product (All)</option>
        <?php while($p = $products->fetch_assoc()): ?>
          <option value="<?= $p['id'] ?>" <?= $filter_product == $p['id'] ? 'selected' : '' ?>>
            <?= htmlspecialchars($p['product_name']) ?>
          </option>
        <?php endwhile; ?>
      </select>

      <input type="date" name="start_date" value="<?= htmlspecialchars($filter_start_date) ?>" />
      <input type="date" name="end_date" value="<?= htmlspecialchars($filter_end_date) ?>" />
      <button type="submit">Apply Filters</button>
    </form>

    <button class="export-btn" onclick="exportCSV()">Export CSV</button>
  </div>

  <table>
    <thead>
      <tr>
        <th>ID</th>
        <th>Product</th>
        <th>From Store</th>
        <th>To Store</th>
        <th>Qty</th>
        <th>Date</th>
        <th>Transferred By</th>
        <th>Notes</th>
      </tr>
    </thead>
    <tbody>
      <?php if ($transfers->num_rows): ?>
        <?php while($row = $transfers->fetch_assoc()): ?>
          <tr>
            <td data-label="ID"><?= $row['id'] ?></td>
            <td data-label="Product"><?= htmlspecialchars($row['product_name']) ?></td>
            <td data-label="From Store"><?= htmlspecialchars($row['from_store_name']) ?></td>
            <td data-label="To Store"><?= htmlspecialchars($row['to_store_name']) ?></td>
            <td data-label="Qty"><?= (int)$row['quantity'] ?></td>
            <td data-label="Date"><?= date('d M Y H:i', strtotime($row['transfer_date'])) ?></td>
            <td data-label="By"><?= htmlspecialchars($row['transferred_by']) ?></td>
            <td data-label="Notes"><?= htmlspecialchars($row['remarks']) ?></td>
          </tr>
        <?php endwhile; ?>
      <?php else: ?>
        <tr><td colspan="8" style="text-align:center;">No transfer records 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() {
  const rows = document.querySelectorAll('table tbody tr');
  if (rows.length === 0) {
    alert('No data to export.');
    return;
  }
  let csv = 'ID,Product,From Store,To Store,Quantity,Date,Transferred By,Notes\n';
  rows.forEach(row => {
    const cells = row.querySelectorAll('td');
    const rowData = Array.from(cells).map(td => `"${td.innerText.replace(/"/g, '""')}"`);
    csv += rowData.join(',') + '\n';
  });
  const a = document.createElement('a');
  a.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
  a.download = 'stock_transfer_log.csv';
  a.click();
}
</script>

</body>
</html>
