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

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}

include_once 'db_connect.php';

$method = $_SERVER['REQUEST_METHOD'];

// 1. GET: Fetch all site images grouped by section
if ($method == 'GET') {
    $query = "SELECT * FROM site_images ORDER BY section_name, display_order ASC";
    $result = $conn->query($query);
    
    $images = [];
    while($row = $result->fetch_assoc()) {
        $images[] = $row;
    }
    echo json_encode(["success" => true, "data" => $images]);
}

// 2. POST: Update or Add a Site Image (With Cleanup on Replace)
if ($method == 'POST') {
    $data = json_decode(file_get_contents("php://input"));
    
    if (!empty($data->image_url) && !empty($data->section_name)) {
        $section = mysqli_real_escape_string($conn, $data->section_name);
        $url = mysqli_real_escape_string($conn, $data->image_url);
        $order = isset($data->display_order) ? intval($data->display_order) : 0;
        $alt_text = $section.'_'.$order;

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

            // Fetch current image path to see if it's being replaced
            $stmt = $conn->prepare("SELECT image_url FROM site_images WHERE id = ?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $res = $stmt->get_result();
            $old_img = $res->fetch_assoc();

            // If the URL has changed, delete the old physical file
            if ($old_img && !empty($old_img['image_url']) && $old_img['image_url'] !== $url) {
                $old_file_path = ".." . $old_img['image_url']; // Prepends ".." to target root from /api
                if (file_exists($old_file_path)) {
                    unlink($old_file_path);
                }
            }

            $query = "UPDATE site_images SET image_url='$url', display_order=$order WHERE id=$id";
        } else {
            // INSERT LOGIC
            $query = "INSERT INTO site_images (section_name, image_url, alt_text, display_order) VALUES ('$section', '$url', '$alt_text', $order)";
        }

        if ($conn->query($query)) {
            echo json_encode(["success" => true, "message" => "Site image updated and storage cleaned."]);
        } else {
            http_response_code(500);
            echo json_encode(["success" => false, "message" => "Update failed: " . $conn->error]);
        }
    } else {
        echo json_encode(["success" => false, "message" => "Incomplete data provided."]);
    }
}

// 3. DELETE: For carousel images specifically (With Physical File Deletion)
if ($method == 'DELETE') {
    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    
    if ($id > 0) {
        // Fetch the image path BEFORE deleting the record
        $stmt = $conn->prepare("SELECT image_url FROM site_images WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $res = $stmt->get_result();
        $img = $res->fetch_assoc();

        if ($img && !empty($img['image_url'])) {
            $file_to_delete = ".." . $img['image_url'];
            
            // Physically delete the file from the folder if it exists
            if (file_exists($file_to_delete)) {
                unlink($file_to_delete);
            }
        }

        $query = "DELETE FROM site_images WHERE id = $id";
        if ($conn->query($query)) {
            echo json_encode(["success" => true, "message" => "Image removed and file deleted."]);
        } else {
            http_response_code(500);
            echo json_encode(["success" => false, "message" => "Database error: " . $conn->error]);
        }
    } else {
        http_response_code(400);
        echo json_encode(["success" => false, "message" => "Invalid image ID provided."]);
    }
}

$conn->close();
?>