<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

session_save_path(__DIR__ . '/../tmp');
if (!is_dir(__DIR__ . '/../tmp')) mkdir(__DIR__ . '/../tmp', 0777, true);
session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: /wood-system/login.php");
    exit;
}

require __DIR__ . '/../includes/db.php';
require __DIR__ . '/../includes/header.php';

$rows = $pdo->query("
  SELECT 
    p.id,
    p.name,
    p.unit,
    p.quantity,
    p.cost_price,
    (p.quantity * p.cost_price) AS total_value,
    (SELECT MAX(pi.date) FROM purchase_invoices pi 
       JOIN purchase_items it ON pi.id = it.invoice_id
       WHERE it.product_id = p.id) AS last_purchase_date
  FROM products p
  ORDER BY p.name
")->fetchAll(PDO::FETCH_ASSOC);
?>

<h3 class="mb-3">📦 إدارة المخزون</h3>

<div class="card shadow-sm">
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-striped text-center align-middle mb-0">
        <thead class="table-dark">
          <tr>
            <th>#</th>
            <th>اسم المنتج</th>
            <th>الوحدة</th>
            <th>الكمية الحالية</th>
            <th>سعر التكلفة ($)</th>
            <th>القيمة الإجمالية ($)</th>
            <th>آخر عملية شراء</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($rows as $r): ?>
          <tr>
            <td><?= $r['id'] ?></td>
            <td><?= htmlspecialchars($r['name']) ?></td>
            <td><?= htmlspecialchars($r['unit']) ?></td>
            <td class="<?= $r['quantity'] < 0 ? 'text-danger fw-bold' : '' ?>">
              <?= number_format($r['quantity'], 2) ?>
            </td>
            <td><?= number_format($r['cost_price'], 2) ?></td>
            <td class="fw-bold text-primary"><?= number_format($r['total_value'], 2) ?></td>
            <td><?= $r['last_purchase_date'] ?: '—' ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<?php require __DIR__ . '/../includes/footer.php'; ?>
