<?php
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';

error_reporting(E_ALL);
ini_set('display_errors', 1);

/* إضافة مخلص جديد */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_agent'])) {
  $name = trim($_POST['name']);
  $phone = trim($_POST['phone']);
  $email = trim($_POST['email']);
  $address = trim($_POST['address']);
  $note = trim($_POST['note']);

  if ($name != '') {
    $stmt = $pdo->prepare("INSERT INTO agents (name,phone,email,address,note) VALUES (?,?,?,?,?)");
    $stmt->execute([$name, $phone, $email, $address, $note]);
  }
  header("Location: agents.php");
  exit;
}

/* تعديل مخلص */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_agent'])) {
  $id = (int)$_POST['id'];
  $name = trim($_POST['name']);
  $phone = trim($_POST['phone']);
  $email = trim($_POST['email']);
  $address = trim($_POST['address']);
  $note = trim($_POST['note']);

  $pdo->prepare("UPDATE agents SET name=?,phone=?,email=?,address=?,note=? WHERE id=?")
      ->execute([$name,$phone,$email,$address,$note,$id]);
  header("Location: agents.php");
  exit;
}

/* حذف مخلص */
if (isset($_GET['delete'])) {
  $pdo->prepare("DELETE FROM agents WHERE id=?")->execute([(int)$_GET['delete']]);
  header("Location: agents.php");
  exit;
}

/* جلب المخلصين */
$rows = $pdo->query("SELECT * FROM agents ORDER BY name ASC")->fetchAll();
?>

<h3 class="mb-3 text-primary">🚛 إدارة المخلصين الجمركيين</h3>

<div class="d-flex justify-content-end mb-3">
  <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addModal">➕ إضافة مخلص جديد</button>
</div>

<div class="card shadow-sm"><div class="card-body p-0">
<div class="table-responsive">
<table class="table table-striped table-hover 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['phone']) ?></td>
  <td><?= htmlspecialchars($r['email']) ?></td>
  <td><?= htmlspecialchars($r['address']) ?></td>
  <td><?= htmlspecialchars($r['note']) ?></td>
  <td>
    <button class="btn btn-sm btn-outline-primary"
            data-bs-toggle="modal"
            data-bs-target="#editModal"
            data-id="<?= $r['id'] ?>"
            data-name="<?= htmlspecialchars($r['name']) ?>"
            data-phone="<?= htmlspecialchars($r['phone']) ?>"
            data-email="<?= htmlspecialchars($r['email']) ?>"
            data-address="<?= htmlspecialchars($r['address']) ?>"
            data-note="<?= htmlspecialchars($r['note']) ?>">✏️ تعديل</button>
    <a href="?delete=<?= $r['id'] ?>" class="btn btn-sm btn-outline-danger"
       onclick="return confirm('هل تريد حذف هذا المخلص؟')">🗑 حذف</a>
  </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div></div></div>

<!-- نافذة الإضافة -->
<div class="modal fade" id="addModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <form method="post" class="modal-content">
      <div class="modal-header bg-success text-white">
        <h5 class="modal-title">إضافة مخلص جديد</h5>
        <button class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body row g-3">
        <div class="col-md-6"><label class="form-label">الاسم *</label><input name="name" class="form-control" required></div>
        <div class="col-md-6"><label class="form-label">الهاتف</label><input name="phone" class="form-control"></div>
        <div class="col-md-6"><label class="form-label">الإيميل</label><input name="email" class="form-control"></div>
        <div class="col-md-6"><label class="form-label">العنوان</label><input name="address" class="form-control"></div>
        <div class="col-md-12"><label class="form-label">ملاحظات</label><textarea name="note" class="form-control"></textarea></div>
      </div>
      <div class="modal-footer"><button class="btn btn-success" name="add_agent">💾 حفظ</button></div>
    </form>
  </div>
</div>

<!-- نافذة التعديل -->
<div class="modal fade" id="editModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <form method="post" class="modal-content">
      <input type="hidden" name="id" id="edit_id">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title">تعديل المخلص</h5>
        <button class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body row g-3">
        <div class="col-md-6"><label class="form-label">الاسم *</label><input name="name" id="edit_name" class="form-control" required></div>
        <div class="col-md-6"><label class="form-label">الهاتف</label><input name="phone" id="edit_phone" class="form-control"></div>
        <div class="col-md-6"><label class="form-label">الإيميل</label><input name="email" id="edit_email" class="form-control"></div>
        <div class="col-md-6"><label class="form-label">العنوان</label><input name="address" id="edit_address" class="form-control"></div>
        <div class="col-md-12"><label class="form-label">ملاحظات</label><textarea name="note" id="edit_note" class="form-control"></textarea></div>
      </div>
      <div class="modal-footer"><button class="btn btn-primary" name="edit_agent">💾 حفظ التعديلات</button></div>
    </form>
  </div>
</div>

<script>
var editModal=document.getElementById('editModal');
editModal.addEventListener('show.bs.modal',e=>{
  var b=e.relatedTarget;
  document.getElementById('edit_id').value=b.dataset.id;
  document.getElementById('edit_name').value=b.dataset.name;
  document.getElementById('edit_phone').value=b.dataset.phone;
  document.getElementById('edit_email').value=b.dataset.email;
  document.getElementById('edit_address').value=b.dataset.address;
  document.getElementById('edit_note').value=b.dataset.note;
});
</script>

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