<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

include_once 'db_connect.php';

$method = $_SERVER['REQUEST_METHOD'];

// 1. GET: Fetch all gallery items
if ($method == 'GET') {
    $query = "SELECT * FROM gallery ORDER BY uploaded_at DESC";
    $result = $conn->query($query);
    
    $gallery = [];
    while($row = $result->fetch_assoc()) {
        $gallery[] = [
            "id" => $row['id'],
            "title" => $row['title'],
            "category" => $row['category'],
            "src" => $row['image_url'],
            "date" => $row['uploaded_at']
        ];
    }
    echo json_encode(["success" => true, "data" => $gallery]);
}

// 2. POST: Add or Update Gallery Item (With Image Cleanup on Update)
if ($method == 'POST') {
    $data = json_decode(file_get_contents("php://input"));
    
    if (!empty($data->src) && !empty($data->category)) {
        $title = mysqli_real_escape_string($conn, $data->title);
        $category = mysqli_real_escape_string($conn, $data->category);
        $src = mysqli_real_escape_string($conn, $data->src);

        if (isset($data->id) && $data->id > 0) {
            // UPDATE LOGIC
            $id = intval($data->id);

            // A. Check for existing image to see if we need to clean up the old file
            $stmt = $conn->prepare("SELECT image_url FROM gallery WHERE id = ?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $res = $stmt->get_result();
            $old_photo = $res->fetch_assoc();

            // B. If the image source has changed, delete the old physical file
            if ($old_photo && !empty($old_photo['image_url']) && $old_photo['image_url'] !== $src) {
                $old_file_path = ".." . $old_photo['image_url'];
                if (file_exists($old_file_path)) {
                    unlink($old_file_path);
                }
            }

            $query = "UPDATE gallery SET title='$title', category='$category', image_url='$src' WHERE id=$id";
        } else {
            // INSERT LOGIC
            $query = "INSERT INTO gallery (title, category, image_url) VALUES ('$title', '$category', '$src')";
        }

        if ($conn->query($query)) {
            echo json_encode(["success" => true, "message" => "Gallery item saved and storage optimized."]);
        } else {
            http_response_code(500);
            echo json_encode(["success" => false, "message" => "Database error: " . $conn->error]);
        }
    }
}

// 3. DELETE: Remove Record & Physically Delete Associated Image
if ($method == 'DELETE') {
    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    
    if ($id > 0) {
        // A. Fetch the image path BEFORE deleting the record
        $stmt = $conn->prepare("SELECT image_url FROM gallery WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $res = $stmt->get_result();
        $photo = $res->fetch_assoc();

        if ($photo && !empty($photo['image_url'])) {
            // Path relative to this script: prepend ".." to target the root directory
            $file_path = ".." . $photo['image_url']; 
            
            // B. Physically delete the file from the folder if it exists
            if (file_exists($file_path)) {
                unlink($file_path);
            }
        }

        // C. Delete the database record
        $query = "DELETE FROM gallery WHERE id = $id";
        if ($conn->query($query)) {
            echo json_encode(["success" => true, "message" => "Photo and associated file deleted."]);
        } else {
            http_response_code(500);
            echo json_encode(["success" => false, "message" => "Database error: " . $conn->error]);
        }
    } else {
        echo json_encode(["success" => false, "message" => "Invalid ID provided."]);
    }
}

$conn->close();
?>