<?php
include 'auth.php';
include_once '../config/database.php';
header('Content-Type: text/html; charset=utf-8');

$message = '';

function handleUpload($file) {
    if (isset($file) && $file['error'] === 0) {
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $filename = uniqid() . '.' . $ext;
        if (!is_dir('../uploads')) mkdir('../uploads');
        $destination = '../uploads/' . $filename;
        if (move_uploaded_file($file['tmp_name'], $destination)) {
            return $filename;
        }
    }
    return null;
}

if (isset($_POST['action'])) {
    if ($_POST['action'] == 'add') {
        $name = $_POST['name'];
        $desc = $_POST['description'];
        $price = $_POST['price'];
        $capacity = $_POST['capacity'];
        $image = handleUpload($_FILES['image']) ?: 'default.png';

        $stmt = $conn->prepare("INSERT INTO games (name, description, price, capacity, image_url) VALUES (?, ?, ?, ?, ?)");
        if ($stmt->execute([$name, $desc, $price, $capacity, $image])) {
            $message = '<div class="alert alert-success alert-dismissible fade show">✅ تم إضافة اللعبة بنجاح! <button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>';
        }
    } elseif ($_POST['action'] == 'edit') {
        $id = $_POST['id'];
        $name = $_POST['name'];
        $desc = $_POST['description'];
        $price = $_POST['price'];
        $capacity = $_POST['capacity'];
        $image = handleUpload($_FILES['image']);

        if ($image) {
            $stmt = $conn->prepare("UPDATE games SET name=?, description=?, price=?, capacity=?, image_url=? WHERE id=?");
            $stmt->execute([$name, $desc, $price, $capacity, $image, $id]);
        } else {
            $stmt = $conn->prepare("UPDATE games SET name=?, description=?, price=?, capacity=? WHERE id=?");
            $stmt->execute([$name, $desc, $price, $capacity, $id]);
        }
        $message = '<div class="alert alert-info alert-dismissible fade show">🔹 تم تحديث بيانات اللعبة بنجاح! <button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>';
    }
}

if (isset($_GET['delete'])) {
    $stmt = $conn->prepare("DELETE FROM games WHERE id = ?");
    $stmt->execute([$_GET['delete']]);
    header("Location: games.php");
    exit;
}

$games = $conn->query("SELECT * FROM games ORDER BY id DESC")->fetchAll();
ob_start();
?>

<style>
    .modal-backdrop { opacity: 0.7 !important; }
    .modal-content { border: none; border-radius: 20px; box-shadow: 0 10px 30px rgba(0,0,0,0.2); }
    .table img { object-fit: cover; border: 2px solid #eee; }
</style>

<?= $message ?>

<div class="card p-4 shadow-sm border-0">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="fw-bold m-0"><i class="fas fa-gamepad me-2 text-primary"></i> إدارة الألعاب</h4>
        <button class="btn btn-primary btn-lg shadow-sm" data-bs-toggle="modal" data-bs-target="#addModal">
            <i class="fas fa-plus-circle me-2"></i> إضافة لعبة جديدة
        </button>
    </div>

    <div class="table-responsive">
        <table class="table table-hover align-middle">
            <thead class="table-light">
                <tr>
                    <th>الصورة</th>
                    <th>اسم اللعبة</th>
                    <th>السعة</th>
                    <th>السعر</th>
                    <th class="text-center">الإجراءات</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($games as $game): ?>
                <tr>
                    <td><img src="../uploads/<?= $game['image_url'] ?>" width="70" height="70" class="rounded-3"></td>
                    <td><div class="fw-bold text-dark fs-5"><?= htmlspecialchars($game['name']) ?></div></td>
                    <td><span class="badge bg-light text-primary border px-3 py-2"><?= $game['capacity'] ?> شخص</span></td>
                    <td><span class="text-success fw-bold fs-5"><?= number_format($game['price'], 2) ?> درهم</span></td>
                    <td class="text-center">
                        <button class="btn btn-outline-primary btn-sm px-3" data-bs-toggle="modal" data-bs-target="#editModal<?= $game['id'] ?>">
                            <i class="fas fa-edit me-1"></i> تعديل
                        </button>
                        <a href="?delete=<?= $game['id'] ?>" class="btn btn-outline-danger btn-sm px-3" onclick="return confirm('حذف اللعبة نهائياً؟')">
                            <i class="fas fa-trash me-1"></i> مسح
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- All Modals (Moved Outside Table for Perfect Layout) -->
<?php foreach($games as $game): ?>
<div class="modal fade" id="editModal<?= $game['id'] ?>" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <form method="POST" enctype="multipart/form-data" class="modal-content overflow-hidden">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title fw-bold">تعديل بيانات: <?= htmlspecialchars($game['name']) ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <input type="hidden" name="action" value="edit">
                <input type="hidden" name="id" value="<?= $game['id'] ?>">
                <div class="mb-3">
                    <label class="form-label fw-bold">اسم اللعبة</label>
                    <input type="text" name="name" class="form-control form-control-lg" value="<?= $game['name'] ?>" required>
                </div>
                <div class="mb-3">
                    <label class="form-label fw-bold">الوصف</label>
                    <textarea name="description" class="form-control" rows="4" required><?= $game['description'] ?></textarea>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-bold">السعر (درهم)</label>
                        <input type="number" step="0.01" name="price" class="form-control form-control-lg text-primary" value="<?= $game['price'] ?>" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-bold">السعة (أشخاص)</label>
                        <input type="number" name="capacity" class="form-control form-control-lg" value="<?= $game['capacity'] ?>" required>
                    </div>
                </div>
                <div class="mb-0">
                    <label class="form-label fw-bold">الصورة (اختياري)</label>
                    <input type="file" name="image" class="form-control" accept="image/*">
                </div>
            </div>
            <div class="modal-footer bg-light">
                <button type="button" class="btn btn-secondary px-4" data-bs-dismiss="modal">إلغاء</button>
                <button type="submit" class="btn btn-primary px-5 fw-bold">حفظ التغييرات</button>
            </div>
        </form>
    </div>
</div>
<?php endforeach; ?>

<!-- Add Modal -->
<div class="modal fade" id="addModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <form method="POST" enctype="multipart/form-data" class="modal-content overflow-hidden">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title fw-bold">إضافة لعبة جديدة</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <input type="hidden" name="action" value="add">
                <div class="mb-3">
                    <label class="form-label fw-bold">اسم اللعبة</label>
                    <input type="text" name="name" class="form-control form-control-lg" placeholder="مثال: قطار الموت" required>
                </div>
                <div class="mb-3">
                    <label class="form-label fw-bold">الوصف</label>
                    <textarea name="description" class="form-control" rows="4" placeholder="وصف ممتع للعبة..." required></textarea>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-bold">السعر</label>
                        <input type="number" step="0.01" name="price" class="form-control form-control-lg text-success" placeholder="0.00" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-bold">السعة</label>
                        <input type="number" name="capacity" class="form-control form-control-lg" placeholder="عدد الأشخاص" required>
                    </div>
                </div>
                <div class="mb-0">
                    <label class="form-label fw-bold">صورة اللعبة</label>
                    <input type="file" name="image" class="form-control" accept="image/*" required>
                </div>
            </div>
            <div class="modal-footer bg-light">
                <button type="button" class="btn btn-secondary px-4" data-bs-dismiss="modal">إلغاء</button>
                <button type="submit" class="btn btn-success px-5 fw-bold">إضافة اللعبة</button>
            </div>
        </form>
    </div>
</div>

<?php
$content = ob_get_clean();
$page_title = 'إدارة الألعاب';
include 'layout.php';
?>
