<?php
session_start();
include_once("../config/db.php");

// Security: Ensure user is an admin before performing any action.
if(!isset($_SESSION['admin'])){
    header("Location: login.php");
    exit();
}
include 'admin_header.php';

$message = '';

if(isset($_POST['submit'])){
    if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
        $allowed = ['jpg', 'jpeg', 'png', 'gif'];
        $filename = $_FILES['image']['name'];
        $filetype = pathinfo($filename, PATHINFO_EXTENSION);

        if (in_array(strtolower($filetype), $allowed)) {
            // Create a unique filename to prevent overwriting
            $new_filename = uniqid('', true) . '.' . $filetype;
            $upload_path = "uploads/" . $new_filename;

            if (move_uploaded_file($_FILES['image']['tmp_name'], $upload_path)) {
                // Use prepared statements to prevent SQL injection
                $sql = "INSERT INTO gallery(image) VALUES(?)";
                $stmt = mysqli_prepare($conn, $sql);
                mysqli_stmt_bind_param($stmt, "s", $new_filename);
                
                if (mysqli_stmt_execute($stmt)) {
                    $message = "<div class='success'>Image Added Successfully.</div>";
                } else {
                    $message = "<div class='error'>Database error: Could not add image.</div>";
                }
            } else {
                $message = "<div class='error'>Error: Could not move uploaded file.</div>";
            }
        } else {
            $message = "<div class='error'>Error: Invalid file type. Only JPG, JPEG, PNG, GIF are allowed.</div>";
        }
    } else {
        $message = "<div class='error'>Error: No file uploaded or an upload error occurred.</div>";
    }
}

?>
<div class="page-header">
    <h1>Add Gallery Image</h1>
    <a href="manage_gallery.php" class="btn">Back to Gallery</a>
</div>

<div class="content-wrapper">
    <?php if(!empty($message)) echo $message; ?>

    <form method="POST" enctype="multipart/form-data">
        <div class="form-group">
            <label for="image">Image File</label>
            <input type="file" id="image" name="image" required>
        </div>
        <button type="submit" name="submit">Upload Image</button>
    </form>
</div>
<?php include 'admin_footer.php'; ?>