<?php
session_start();

// Check if the admin is logged in
if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: login.php"); // Redirect to login page if not logged in
    exit;
}

// Slider directory
$sliderDir = 'slider/';

// Array of slider file names
$sliderFiles = [
    'slider-1.png',
    'slider-2.png',
    'slider-3.png',
    'slider-4.png',
    'slider-5.png'
];

// Handle the image upload
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $sliderNumber = $_POST['slider_number']; // Slider number (1-5)
    
    // Ensure the file is uploaded correctly
    if (isset($_FILES['slider_image']) && $_FILES['slider_image']['error'] === UPLOAD_ERR_OK) {
        $sliderFile = $sliderDir . 'slider-' . $sliderNumber . '.png';

        // Check if the old file exists and delete it
        if (file_exists($sliderFile)) {
            unlink($sliderFile); // Delete the old slider image
        }

        // Move the uploaded file to the slider folder
        $uploadedFile = $_FILES['slider_image']['tmp_name'];
        if (move_uploaded_file($uploadedFile, $sliderFile)) {
            echo json_encode(['status' => 'success']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Error uploading the image!']);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'No image uploaded or error occurred!']);
    }
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Slider Images</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
        }
        .header {
            display: flex;
            align-items: center;
            background-color: #4CAF50;
            color: white;
            padding: 15px;
            text-align: center;
            justify-content: space-between;
        }
        .back-icon {
            cursor: pointer;
        }
        .back-icon img {
            width: 18px;
            height: 18px;
        }
        .container {
            max-width: 800px;
            margin: 20px auto;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .slider-images {
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
        }
        .slider-images div {
            flex: 0 0 48%;
            margin-bottom: 20px;
            text-align: center;
        }
        .slider-images img {
            max-width: 100%;
            cursor: pointer;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        input[type="file"] {
            display: none;
        }
    </style>
</head>
<body>

<!-- Header Section -->
<div class="header">
    <div class="back-icon" onclick="window.history.back()">
        <img src="https://cdn-icons-png.flaticon.com/512/93/93634.png" alt="Back">
    </div>
    <h2>Manage Slider Images</h2>
</div>

<!-- Main Container -->
<div class="container">
    <div class="slider-images">
        <?php foreach ($sliderFiles as $index => $sliderFile): ?>
            <div>
                <h4>Slider <?php echo $index + 1; ?></h4>
                <img src="<?php echo $sliderDir . $sliderFile; ?>" alt="Slider <?php echo $index + 1; ?>" id="slider-<?php echo $index + 1; ?>-preview" onclick="document.getElementById('slider-<?php echo $index + 1; ?>-input').click()">
                <input type="file" id="slider-<?php echo $index + 1; ?>-input" accept="image/*" onchange="uploadSliderImage(<?php echo $index + 1; ?>)">
            </div>
        <?php endforeach; ?>
    </div>
</div>

<script>
    function uploadSliderImage(sliderNumber) {
        const fileInput = document.getElementById('slider-' + sliderNumber + '-input');
        const formData = new FormData();
        formData.append('slider_image', fileInput.files[0]);
        formData.append('slider_number', sliderNumber);

        fetch('', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                const reader = new FileReader();
                reader.onload = function (e) {
                    document.getElementById('slider-' + sliderNumber + '-preview').src = e.target.result;
                }
                reader.readAsDataURL(fileInput.files[0]);
                alert('Slider ' + sliderNumber + ' image updated successfully!');
            } else {
                alert('Error: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error uploading image:', error);
            alert('Error uploading the image. Please try again.');
        });
    }
</script>

</body>
</html>
