<?php
session_start();
require_once('../config/db.php');

if (!isset($_SESSION['user'])) {
    header('Location: ../auth/login.php');
    exit;
}

// حذف مسوّق إذا تم طلب delete
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $stmt = $conn->prepare("DELETE FROM marketers WHERE id = ?");
    $stmt->execute([$id]);
    header('Location: list.php');
    exit;
}

// جلب قائمة المسوّقين
$stmt = $conn->query("SELECT * FROM marketers ORDER BY name ASC");
$marketers = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>قائمة المسوّقين</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>body { font-family: 'Cairo', sans-serif; }</style>
</head>
<body class="bg-gray-100 p-6">
<div class="max-w-6xl mx-auto">

<h1 class="text-3xl font-bold mb-6 text-center">قائمة المسوّقين</h1>

<div class="mb-4 text-right">
    <a href="add.php" class="bg-green-600 text-white px-4 py-2 rounded-md hover:bg-green-700">إضافة مسوّق</a>
</div>

<table class="min-w-full table-auto border border-gray-200 bg-white rounded-md overflow-hidden">
    <thead class="bg-gray-50">
        <tr class="text-gray-700">
            <th class="border px-4 py-2 text-right">#</th>
            <th class="border px-4 py-2 text-right">اسم المسوّق</th>
            <th class="border px-4 py-2 text-center">إجراءات</th>
        </tr>
    </thead>
    <tbody>
        <?php if ($marketers): foreach ($marketers as $index => $m): ?>
        <tr class="hover:bg-gray-50">
            <td class="border px-4 py-2 text-right"><?= $index + 1 ?></td>
            <td class="border px-4 py-2 text-right"><?= htmlspecialchars($m['name']) ?></td>
            <td class="border px-4 py-2 text-center space-x-2">
                <a href="edit.php?id=<?= $m['id'] ?>" class="bg-yellow-500 text-white px-3 py-1 rounded hover:bg-yellow-600">تعديل</a>
                <a href="list.php?delete=<?= $m['id'] ?>" onclick="return confirm('هل أنت متأكد من الحذف؟');" class="bg-red-600 text-white px-3 py-1 rounded hover:bg-red-700">حذف</a>
            </td>
        </tr>
        <?php endforeach; else: ?>
        <tr>
            <td class="border px-4 py-2 text-center" colspan="3">لا يوجد مسوّقين</td>
        </tr>
        <?php endif; ?>
    </tbody>
</table>

</div>
</body>
</html>
