<?php
/**
 * sliders.php - إدارة العروض
 * @version 5.0.0
 */

require_once 'config.php';
checkAdminAuth();

// ============================================
// معالجة النماذج
// ============================================

// إضافة صورة
if (isPost() && isset($_POST['add'])) {
    if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
        $upload = uploadImage($_FILES['image']);
        if ($upload['success']) {
            $active = isset($_POST['active']) ? 1 : 0;
            $conn->query("INSERT INTO sliders (image, is_active, created_at) VALUES ('{$upload['filename']}', $active, NOW())");
            $cache->clear();
            $_SESSION['success'] = 'تم إضافة الصورة بنجاح';
        } else {
            $_SESSION['error'] = $upload['message'];
        }
    } else {
        $_SESSION['error'] = 'يرجى اختيار صورة';
    }
    header('Location: sliders.php');
    exit();
}

// تغيير حالة الصورة
if (isPost() && isset($_POST['toggle'])) {
    $id = (int)$_POST['id'];
    $conn->query("UPDATE sliders SET is_active = NOT is_active WHERE id=$id");
    $cache->clear();
    header('Location: sliders.php');
    exit();
}

// حذف صورة
if (isPost() && isset($_POST['delete'])) {
    $id = (int)$_POST['id'];
    $slider = $conn->query("SELECT image FROM sliders WHERE id=$id")->fetch_assoc();
    if ($slider['image']) deleteImage($slider['image']);
    $conn->query("DELETE FROM sliders WHERE id=$id");
    $cache->clear();
    $_SESSION['success'] = 'تم حذف الصورة بنجاح';
    header('Location: sliders.php');
    exit();
}

// ============================================
// جلب البيانات
// ============================================

$sliders = $cache->get('sliders_list');
if (!$sliders) {
    $result = $conn->query("SELECT * FROM sliders ORDER BY id DESC LIMIT 50");
    $sliders = [];
    while ($row = $result->fetch_assoc()) {
        $sliders[] = $row;
    }
    $cache->set('sliders_list', $sliders, 300);
}

$page_title = 'العروض';
include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
.slider-img {
    width: 100%;
    height: 180px;
    object-fit: cover;
    transition: transform 0.3s;
}

.slider-card:hover .slider-img {
    transform: scale(1.05);
}

.slider-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(to top, rgba(0,0,0,0.5), transparent);
    opacity: 0;
    transition: opacity 0.3s;
    display: flex;
    align-items: flex-end;
    padding: 1rem;
}

.slider-card:hover .slider-overlay {
    opacity: 1;
}
</style>

<div class="main-content">
    <div class="top-bar">
        <i class="bi bi-images text-primary fs-4 me-2"></i>
        <span><strong>إدارة العروض</strong></span>
        <span class="ms-auto text-muted small">
            <i class="bi bi-grid-3x3-gap-fill me-1"></i><?php echo count($sliders); ?> صورة
        </span>
    </div>

    <!-- زر الإضافة -->
    <div class="d-flex justify-content-end mb-3">
        <button class="btn btn-primary" onclick="openAddModal()">
            <i class="bi bi-plus-lg me-1"></i>إضافة صورة جديدة
        </button>
    </div>

    <!-- Grid عرض الصور -->
    <div class="row g-3">
        <?php if (empty($sliders)): ?>
        <div class="col-12">
            <div class="card text-center p-5">
                <i class="bi bi-images display-1 text-muted mb-3"></i>
                <h6>لا توجد صور</h6>
                <p class="text-muted small">قم بإضافة أول صورة الآن</p>
                <button class="btn btn-primary mx-auto" style="width: fit-content;" onclick="openAddModal()">
                    <i class="bi bi-plus-lg me-1"></i>إضافة
                </button>
            </div>
        </div>
        <?php endif; ?>
        
        <?php foreach ($sliders as $s): ?>
        <div class="col-md-4 col-6">
            <div class="card slider-card overflow-hidden">
                <div style="position: relative;">
                    <img src="uploads/<?php echo $s['image']; ?>" class="slider-img" loading="lazy">
                    <div class="slider-overlay">
                        <div class="w-100">
                            <div class="d-flex justify-content-between align-items-center">
                                <span class="badge bg-<?php echo $s['is_active'] ? 'success' : 'secondary'; ?>">
                                    <?php echo $s['is_active'] ? 'نشط' : 'غير نشط'; ?>
                                </span>
                                <small class="text-white"><?php echo date('Y-m-d', strtotime($s['created_at'])); ?></small>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-body p-2">
                    <div class="d-flex gap-2">
                        <form method="POST" class="flex-grow-1">
                            <input type="hidden" name="id" value="<?php echo $s['id']; ?>">
                            <button type="submit" name="toggle" class="btn btn-sm w-100 <?php echo $s['is_active'] ? 'btn-warning' : 'btn-success'; ?>">
                                <i class="bi bi-<?php echo $s['is_active'] ? 'pause' : 'play'; ?> me-1"></i>
                                <?php echo $s['is_active'] ? 'تعطيل' : 'تفعيل'; ?>
                            </button>
                        </form>
                        <form method="POST" onsubmit="return confirm('تأكيد حذف الصورة؟')">
                            <input type="hidden" name="id" value="<?php echo $s['id']; ?>">
                            <button type="submit" name="delete" class="btn btn-sm btn-danger">
                                <i class="bi bi-trash"></i>
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- مودال إضافة صورة -->
<div class="modal fade" id="addModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">إضافة صورة جديدة</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" enctype="multipart/form-data">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label small">اختر الصورة</label>
                        <input type="file" class="form-control" name="image" accept="image/*" required>
                        <small class="text-muted">JPG, PNG, GIF - حد أقصى 5MB</small>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="active" id="active" checked>
                        <label class="form-check-label" for="active">نشط</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" name="add" class="btn btn-primary">رفع</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function openAddModal() {
    new bootstrap.Modal(document.getElementById('addModal')).show();
}
</script>

<?php include 'includes/footer.php'; ?>