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

// معالجة إضافة المادة
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $notes = trim($_POST['notes'] ?? '');
    if ($name) {
        $stmt = $pdo->prepare('INSERT INTO products (name, notes) VALUES (?, ?)');
        $stmt->execute([$name, $notes]);
        header("Location: products.php?success=1");
        exit;
    }
}

// جلب جميع المواد
$products = $pdo->query('SELECT * FROM products ORDER BY id 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; }
.card { border-radius: 15px; }
</style>
</head>
<body>

<?php include 'navbar.php'; ?> <!-- ✅ تم نقلها هنا داخل الـ body -->

<div class="container py-4">
  <h3 class="mb-3 text-center">🧱 إدارة المواد</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">
      <div class="col-12 col-md-5">
        <input name="name" class="form-control" placeholder="اسم المادة" required>
      </div>
      <div class="col-12 col-md-5">
        <input name="notes" class="form-control" placeholder="ملاحظات">
      </div>
      <div class="col-12 col-md-2 d-grid">
        <button class="btn btn-success">➕ إضافة</button>
      </div>
    </div>
  </form>

  <div class="table-responsive shadow-sm">
    <table class="table table-bordered bg-white text-center align-middle">
      <thead class="table-success">
        <tr><th>الاسم</th><th>ملاحظات</th></tr>
      </thead>
      <tbody>
      <?php foreach ($products as $p): ?>
        <tr>
          <td><?= htmlspecialchars($p['name']) ?></td>
          <td><?= htmlspecialchars($p['notes']) ?></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>
