
<?php
ob_start();
include("connection.php");

// Add new gallery
if(isset($_POST['add_gallery'])) {
    $categoryId = mysqli_real_escape_string($conn, $_POST['category_id']);
    
    // Handle file upload - check if file is uploaded
    $fileName = '';
    if(isset($_FILES["image"]) && $_FILES["image"]["error"] == 0 && !empty($_FILES["image"]["name"])) {
        $targetDir = "gallery_images/";
        $fileName = time() . "_" . basename($_FILES["image"]["name"]);
        $targetFile = $targetDir . $fileName;
        $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
        $allowedTypes = ['jpg','jpeg','png','gif'];
        
        if(in_array($imageFileType,$allowedTypes)) {
            if(!move_uploaded_file($_FILES["image"]["tmp_name"], $targetFile)) {
                $fileName = ''; // Reset if upload fails
            }
        } else {
            $fileName = ''; // Reset if file type not allowed
        }
    }
    
    $createdAt = date('Y-m-d H:i:s');

    // Insert gallery
    $sql = mysqli_query($conn, "
        INSERT INTO `gallery` (`category_id`, `image`, `created_at`)
        VALUES ('$categoryId', '$fileName', '$createdAt')
    ");

    if($sql) {
        echo "Gallery added successfully!";
    } else {
        echo "Error: " . mysqli_error($conn);
    }
}

// Fetch gallery data for edit
if(isset($_POST['fetch_gallery'])) {
    $galleryId = mysqli_real_escape_string($conn, $_POST['gallery_id']);
    $q = mysqli_query($conn,"
        SELECT * FROM gallery 
        WHERE id='$galleryId'
        ORDER BY id ASC LIMIT 1
    ");
    $data = mysqli_fetch_assoc($q);
    
    echo json_encode([
        "id" => $data['id'],
        "category_id" => $data['category_id'],
        "image" => $data['image']
    ]);
    exit;
}

// Edit gallery details
if(isset($_POST['edit_gallery'])) {
    $galleryId = mysqli_real_escape_string($conn, $_POST['id']);
    $categoryId = mysqli_real_escape_string($conn, $_POST['category_id']);
    
    // Handle file upload - check if file is uploaded
    $fileName = '';
    if(isset($_FILES["image"]) && $_FILES["image"]["error"] == 0 && !empty($_FILES["image"]["name"])) {
        $targetDir = "gallery_images/";
        $fileName = time() . "_" . basename($_FILES["image"]["name"]);
        $targetFile = $targetDir . $fileName;
        $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
        $allowedTypes = ['jpg','jpeg','png','gif'];
        
        if(in_array($imageFileType,$allowedTypes)) {
            if(!move_uploaded_file($_FILES["image"]["tmp_name"], $targetFile)) {
                $fileName = ''; // Reset if upload fails
            }
        } else {
            $fileName = ''; // Reset if file type not allowed
        }
    }

    // Update gallery
    $sql = mysqli_query($conn, "
        UPDATE `gallery` 
        SET `category_id`='$categoryId'
        WHERE `id`='$galleryId'
    ");
    
    if($fileName != '') {
        $sql = mysqli_query($conn, "
            UPDATE `gallery` SET `image`='$fileName' WHERE `id`='$galleryId'
        ");
    }

    if ($sql) {
        if (mysqli_affected_rows($conn) > 0) {
            echo "Gallery updated successfully!";
        } else {
            echo "No changes made to gallery data.";
        }
    } else {
        echo "Error updating gallery: " . mysqli_error($conn);
    }
}

// Delete gallery
if(isset($_POST['delete_gallery'])) {
    $galleryId = mysqli_real_escape_string($conn, $_POST['gallery_id']);
    $q = mysqli_query($conn,"
        DELETE FROM `gallery` WHERE `id`='$galleryId'
    ");
    if($q) {
        echo "Gallery deleted successfully!";
    } else {
        echo "Error deleting gallery: " . mysqli_error($conn);
    }
    exit;
}
?>
