<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();

// Vérifie si l'admin est bien connecté
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: admin_login.php');
    exit;
}
// 🔒 Optionnel mais recommandé : vérifier l'IP et le User-Agent
// (utile si tu veux bloquer le partage de session)
if (
    ($_SESSION['ip'] ?? '') !== ($_SERVER['REMOTE_ADDR'] ?? '') ||
    ($_SESSION['user_agent'] ?? '') !== ($_SERVER['HTTP_USER_AGENT'] ?? '')
) {
    session_destroy();
    header('Location: admin_login.php?error=session_hijack');
    exit;
}


// Connexion BDD
try {
    $pdo = new PDO("mysql:host=localhost;dbname=tostrlgj_mariage_db;charset=utf8mb4", 'tostrlgj_voldy', 'Voldy25@Ilus', [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    ]);
} catch (Exception $e) {
    die("Erreur DB : " . $e->getMessage());
}

// Dossiers de destination
// Dans admin_photos.php, ajoute une section :
$uploadDirs = [
    'hero' => '../uploads/carousel_hero/',
    'moments' => '../uploads/carousel_moments/',
    'pagne' => '../uploads/carousel_pagne/',
    'groom' => '../uploads/couple/groom/',    // Marié
    'bride' => '../uploads/couple/bride/'     // Mariée
];
// Créer les dossiers s'ils n'existent pas
foreach ($uploadDirs as $dir) {
    if (!is_dir($dir)) {
        mkdir($dir, 0755, true);
    }
}

$message = '';
$messageType = '';

// Traiter les uploads
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'upload') {
    $section = $_POST['section'] ?? '';
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $order_position = (int)($_POST['order_position'] ?? 0);

    if (!isset($_FILES['photo']) || $_FILES['photo']['error'] !== UPLOAD_ERR_OK) {
        $message = 'Erreur : Veuillez sélectionner une photo';
        $messageType = 'error';
    } elseif (!array_key_exists($section, $uploadDirs)) {
        $message = 'Erreur : Section invalide';
        $messageType = 'error';
    } else {
        $file = $_FILES['photo'];
        $fileName = basename($file['name']);
        $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        $allowedExts = ['jpg', 'jpeg', 'png', 'webp', 'gif'];

        if (!in_array($fileExt, $allowedExts)) {
            $message = 'Erreur : Format de fichier non autorisé (JPG, PNG, WEBP, GIF uniquement)';
            $messageType = 'error';
        } elseif ($file['size'] > 5 * 1024 * 1024) {
            $message = 'Erreur : La photo ne doit pas dépasser 5MB';
            $messageType = 'error';
        } else {
            // Générer un nom unique
            $newFileName = time() . '_' . uniqid() . '.' . $fileExt;
            $uploadPath = $uploadDirs[$section] . $newFileName;

            // Générer un nom unique
            $newFileName = time() . '_' . uniqid() . '.' . $fileExt;
            $uploadPath = $uploadDirs[$section] . $newFileName;

            // ✅ Redimensionner et compresser
            if (resizeAndCompressImage($file['tmp_name'], $uploadPath, 1200, 800, 80)) {
                // Sauvegarder en BDD
                $stmt = $pdo->prepare("INSERT INTO carousel_images (section, filename, title, description, order_position) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$section, $newFileName, $title, $description, $order_position]);
                $message = 'Photo uploadée et optimisée avec succès !';
                $messageType = 'success';
            } else {
                $message = 'Erreur : Impossible de traiter l’image (format non supporté ou corrompu).';
                $messageType = 'error';
            }
        }
    }
}

// Traiter les suppressions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete') {
    $id = (int)$_POST['id'] ?? 0;

    // Récupérer le fichier
    $stmt = $pdo->prepare("SELECT section, filename FROM carousel_images WHERE id = ?");
    $stmt->execute([$id]);
    $photo = $stmt->fetch();

    if ($photo) {
        $filePath = $uploadDirs[$photo['section']] . $photo['filename'];
        if (file_exists($filePath)) {
            unlink($filePath);
        }

        // Supprimer de la BDD
        $deleteStmt = $pdo->prepare("DELETE FROM carousel_images WHERE id = ?");
        $deleteStmt->execute([$id]);

        $message = 'Photo supprimée avec succès !';
        $messageType = 'success';
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    }
}

// Récupérer les photos par section
$sections = ['hero', 'moments', 'pagne'];
$photos = [];

foreach ($sections as $sec) {
    $stmt = $pdo->prepare("SELECT * FROM carousel_images WHERE section = ? ORDER BY order_position ASC");
    $stmt->execute([$sec]);
    $photos[$sec] = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>

<!DOCTYPE html>
<html lang="fr">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Gestion des Photos</title>
    <link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;700;900&family=Montserrat:wght@300;400;500;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Montserrat', sans-serif;
            background: linear-gradient(135deg, #f5f5f2 0%, #e8e6e1 100%);
            color: #2c2c2c;
            min-height: 100vh;
            padding: 2rem;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .back-button {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            color: #d4a574;
            text-decoration: none;
            font-weight: 600;
            margin-bottom: 2rem;
            transition: all 0.3s ease;
        }

        .back-button:hover {
            color: #8b6f47;
            transform: translateX(-5px);
        }

        .header {
            text-align: center;
            margin-bottom: 3rem;
        }

        .header h1 {
            font-family: 'Playfair Display', serif;
            font-size: 2.5rem;
            color: #d4a574;
            margin-bottom: 0.5rem;
        }

        .message {
            padding: 1.5rem;
            border-radius: 10px;
            margin-bottom: 2rem;
            display: flex;
            align-items: center;
            gap: 1rem;
            animation: slideIn 0.3s ease;
        }

        .message.success {
            background: #d4f1d4;
            border-left: 4px solid #28a745;
            color: #155724;
        }

        .message.error {
            background: #f8d7da;
            border-left: 4px solid #dc3545;
            color: #721c24;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .sections-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(380px, 1fr));
            gap: 2rem;
        }

        .section-card {
            background: white;
            border-radius: 15px;
            padding: 2rem;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }

        .section-title {
            font-family: 'Playfair Display', serif;
            font-size: 1.8rem;
            color: #d4a574;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .upload-area {
            border: 2px dashed #d4a574;
            border-radius: 10px;
            padding: 2rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-bottom: 1.5rem;
        }

        .upload-area:hover {
            background: rgba(212, 165, 116, 0.05);
            border-color: #8b6f47;
        }

        .upload-icon {
            font-size: 2.5rem;
            color: #d4a574;
            margin-bottom: 1rem;
        }

        .upload-text {
            color: #666;
            font-size: 0.9rem;
        }

        .form-group {
            margin-bottom: 1rem;
        }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
            color: #2c2c2c;
            font-size: 0.9rem;
        }

        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-family: 'Montserrat', sans-serif;
            font-size: 0.9rem;
            transition: border 0.3s ease;
        }

        .form-group input:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #d4a574;
            box-shadow: 0 0 0 3px rgba(212, 165, 116, 0.1);
        }

        .btn-upload {
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            color: white;
            width: 100%;
            padding: 0.75rem;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .btn-upload:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(212, 165, 116, 0.3);
        }

        .photos-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
            gap: 1rem;
            margin-top: 1.5rem;
        }

        .photo-item {
            position: relative;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease;
        }

        .photo-item:hover {
            transform: scale(1.05);
        }

        .photo-item img {
            width: 100%;
            height: 120px;
            object-fit: cover;
            display: block;
        }

        .photo-info {
            padding: 0.5rem;
            background: #f9f9f7;
            font-size: 0.75rem;
            color: #666;
        }

        .photo-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.7);
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .photo-item:hover .photo-overlay {
            opacity: 1;
        }

        .photo-delete-btn {
            background: #dc3545;
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 5px;
            cursor: pointer;
            font-size: 0.85rem;
            transition: all 0.3s ease;
        }

        .photo-delete-btn:hover {
            background: #c82333;
        }

        .photos-empty {
            text-align: center;
            color: #999;
            padding: 2rem;
            font-style: italic;
        }

        @media (max-width: 768px) {
            .sections-grid {
                grid-template-columns: 1fr;
            }

            .header h1 {
                font-size: 1.8rem;
            }
        }
    </style>
</head>

<body>
    <div class="container">
        <a href="admin_dashboard.php" class="back-button">
            <i class="fas fa-arrow-left"></i> Retour au Dashboard
        </a>

        <div class="header">
            <h1>📸 Gestion des Photos</h1>
            <p>Gérez les photos de vos carousels de mariage</p>
        </div>

        <?php if ($message): ?>
            <div class="message <?php echo $messageType; ?>">
                <i class="fas fa-<?php echo $messageType === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
                <span><?php echo htmlspecialchars($message); ?></span>
            </div>
        <?php endif; ?>

        <div class="sections-grid">
            <?php foreach (['hero' => 'Carousel Hero', 'moments' => 'Moments Précieux', 'pagne' => 'Pagne Traditionnel', 'groom' => 'Le Marié', 'bride' => 'La Mariée'] as $key => $label): ?>
                <div class="section-card">
                    <h2 class="section-title">
                        <i class="fas fa-<?= $key === 'hero' ? 'image' : ($key === 'moments' ? 'heart' : 'palette') ?>"></i> <?= $label ?>
                    </h2>

                    <form method="POST" enctype="multipart/form-data">
                        <div class="upload-area" onclick="document.getElementById('<?= $key ?>Input').click()">
                            <div class="upload-icon">
                                <i class="fas fa-cloud-upload-alt"></i>
                            </div>
                            <p class="upload-text">Cliquez pour uploader</p>
                        </div>

                        <input type="hidden" name="action" value="upload">
                        <input type="hidden" name="section" value="<?= $key ?>">
                        <input type="file" id="<?= $key ?>Input" name="photo" accept="image/*" style="display: none;" onchange="this.form.submit()">

                        <div class="form-group">
                            <label>Titre (optionnel)</label>
                            <input type="text" name="title" placeholder="Ex: Notre première rencontre">
                        </div>

                        <div class="form-group">
                            <label>Description (optionnel)</label>
                            <textarea name="description" rows="2" placeholder="Décrivez cette photo..."></textarea>
                        </div>

                        <div class="form-group">
                            <label>Ordre d'affichage</label>
                            <input type="number" name="order_position" value="0" min="0">
                        </div>

                        <button type="submit" class="btn-upload">
                            <i class="fas fa-upload"></i> Uploader
                        </button>
                    </form>

                    <div class="photos-grid">
                        <?php if (empty($photos[$key])): ?>
                            <div class="photos-empty">Aucune photo</div>
                        <?php else: ?>
                            <?php foreach ($photos[$key] as $photo): ?>
                                <div class="photo-item">
                                    <img src="<?= htmlspecialchars($uploadDirs[$key] . $photo['filename']) ?>" alt="<?= $photo['title'] ?>">
                                    <div class="photo-info">
                                        <strong><?= substr($photo['title'] ?: $photo['filename'], 0, 15) ?></strong>
                                    </div>
                                    <div class="photo-overlay">
                                        <form method="POST" style="display: inline;">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="id" value="<?= $photo['id'] ?>">
                                            <button type="submit" class="photo-delete-btn" onclick="return confirm('Supprimer cette photo ?')">
                                                <i class="fas fa-trash"></i> Supprimer
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</body>

</html>