<?php
session_start();
require 'config.php';
if (empty($_SESSION['user'])) header('Location: login.php');

// --- عند الإضافة ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $product_id = $_POST['product_id'] ?? 0;
    $bags = $_POST['bags_count'] ?? 0;
    $weight = $_POST['weight_per_bag'] ?? 0;

    if ($product_id && $bags && $weight) {
        $total = $bags * $weight;

        // تحقق إن كانت المادة موجودة في المخزون
        $check = $pdo->prepare("SELECT * FROM stock WHERE product_id = ?");
        $check->execute([$product_id]);
        $existing = $check->fetch();

        if ($existing) {
            // تحديث المخزون الحالي
            $pdo->prepare("UPDATE stock SET bags_count = bags_count + ?, total_weight = total_weight + ? WHERE product_id = ?")
                ->execute([$bags, $total, $product_id]);
        } else {
            // إدخال جديد
            $stmt = $pdo->prepare('INSERT INTO stock (product_id, bags_count, weight_per_bag, total_weight, date_added) VALUES (?, ?, ?, ?, NOW())');
            $stmt->execute([$product_id, $bags, $weight, $total]);
        }

        // تسجيل الحركة في stock_movements
        $stmt = $pdo->prepare('INSERT INTO stock_movements(product_id, bags_count, total_weight, movement_type, date_added) VALUES (?,?,?,?,NOW())');
        $stmt->execute([$product_id, $bags, $total, 'addition']);

        header("Location: stock.php?success=1");
        exit;
    }
}

// --- جلب البيانات ---
$products = $pdo->query('SELECT id, name FROM products ORDER BY name ASC')->fetchAll();
$stock = $pdo->query('SELECT s.*, p.name FROM stock s JOIN products p ON p.id = s.product_id ORDER BY s.id DESC')->fetchAll();

// --- جلب حركات المخزون ---
$movements = $pdo->query('SELECT m.*, p.name FROM stock_movements m JOIN products p ON p.id=m.product_id ORDER BY m.date_added DESC')->fetchAll();
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<title>📦 إدارة المخزون</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body { background-color: #f8f9fa; }
.table thead th, .table tbody td { text-align:center; vertical-align:middle; }
.card { border-radius: 15px; }
</style>
</head>
<body>

<?php include 'navbar.php'; ?>

<div class="container py-4">
  <h3 class="text-center mb-4">📦 إدارة المخزون</h3>

  <?php if (!empty($_GET['success'])): ?>
    <div class="alert alert-success text-center">✅ تم تحديث المخزون بنجاح!</div>
  <?php endif; ?>

  <!-- نموذج إضافة المخزون -->
  <form method="post" class="card p-3 mb-4 shadow-sm">
    <div class="row g-2 align-items-end">
      <div class="col-12 col-md-4">
        <label class="form-label">المادة</label>
        <select name="product_id" class="form-select" required>
          <option value="">اختر المادة</option>
          <?php foreach($products as $p): ?>
            <option value="<?=$p['id']?>"><?=$p['name']?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-12 col-md-3">
        <label class="form-label">عدد الشوالات</label>
        <input type="number" name="bags_count" class="form-control" min="1" required>
      </div>
      <div class="col-12 col-md-3">
        <label class="form-label">وزن الشوال (كغ)</label>
        <input type="number" step="0.01" name="weight_per_bag" class="form-control" required>
      </div>
      <div class="col-12 col-md-2 d-grid">
        <button class="btn btn-primary">➕ إضافة</button>
      </div>
    </div>
  </form>

  <!-- جدول المخزون الحالي -->
  <div class="table-responsive shadow-sm mb-4">
    <h5>📦 المخزون الحالي</h5>
    <table class="table table-bordered bg-white">
      <thead class="table-primary">
        <tr>
          <th>المادة</th>
          <th>عدد الشوالات</th>
          <th>الوزن الكلي (كغ)</th>
          <th>وزن الشوال (كغ)</th>
          <th>تاريخ الإضافة</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($stock as $s): ?>
        <tr>
          <td><?=$s['name']?></td>
          <td><?=$s['bags_count']?></td>
          <td><?=$s['total_weight']?></td>
          <td><?=$s['weight_per_bag']?></td>
          <td><?=$s['date_added']?></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <!-- جدول حركات المخزون -->
  <div class="table-responsive shadow-sm">
    <h5>📊 حركات المخزون</h5>
    <table class="table table-bordered bg-white">
      <thead class="table-secondary">
        <tr>
          <th>المادة</th>
          <th>عدد الشوالات</th>
          <th>الوزن الكلي (كغ)</th>
          <th>نوع الحركة</th>
          <th>تاريخ الحركة</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($movements as $m): ?>
        <tr>
          <td><?=$m['name']?></td>
          <td><?=$m['bags_count']?></td>
          <td><?=$m['total_weight']?></td>
          <td><?=($m['movement_type'] === 'addition' ? 'إضافة' : 'بيع')?></td>
          <td><?=$m['date_added']?></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <a href="index.php" class="btn btn-secondary mt-3 w-100">🔙 رجوع</a>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
