<?php
// --- CONFIGURATION AND SETUP ---
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once '../config/cors.php';
require_once '../config/database.php';

// --- CONSTANTS ---
define('UPLOAD_DIR', __DIR__ . '/../uploads/carousel/');
define('MAX_FILE_SIZE', 50 * 1024 * 1024); // 50 MB

// --- DATABASE CONNECTION ---
$database = new Database();
$db = $database->getConnection();

// --- HELPER FUNCTIONS ---

/**
 * Generates the full public URL for a given image filename.
 * @param string $imageName The name of the image file.
 * @return string The full URL.
 */
function getImageUrl($imageName) {
    if (empty($imageName)) {
        return null;
    }
    // Adjust the base URL to match your server's public URL structure
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
    $baseUrl = $protocol . $_SERVER['HTTP_HOST'] . "/api/uploads/carousel/";
    return $baseUrl . $imageName;
}

/**
 * Handles the file upload process, including validation and moving the file.
 * Deletes the old image if a new one is provided.
 * @param string|null $oldImageName The filename of the image to be replaced.
 * @return string|null The new unique filename if upload is successful, otherwise null.
 */
function handleImageUpload($oldImageName = null) {
    if (empty($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
        return null; // No new file uploaded or an error occurred
    }

    $image = $_FILES['image'];

    // Validate file size
    if ($image['size'] > MAX_FILE_SIZE) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Image size exceeds the 50MB limit.']);
        exit;
    }

    // Generate a unique name and move the file
    $imageFileType = strtolower(pathinfo($image['name'], PATHINFO_EXTENSION));
    $newImageName = uniqid('carousel_', true) . '.' . $imageFileType;
    $targetFile = UPLOAD_DIR . $newImageName;

    if (!move_uploaded_file($image['tmp_name'], $targetFile)) {
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => 'Failed to save the uploaded image.']);
        exit;
    }

    // If a new image was uploaded successfully, delete the old one
    if ($oldImageName && file_exists(UPLOAD_DIR . $oldImageName)) {
        unlink(UPLOAD_DIR . $oldImageName);
    }

    return $newImageName;
}

// --- API ROUTING ---
$method = $_SERVER['REQUEST_METHOD'];

// Create the upload directory if it doesn't exist
if (!is_dir(UPLOAD_DIR)) {
    mkdir(UPLOAD_DIR, 0777, true);
}

switch ($method) {
    case 'GET':
        $stmt = $db->prepare("
            SELECT hc.*, c.name as category_name, p.name as product_name
            FROM home_carousel hc
            LEFT JOIN categories c ON hc.category_id = c.id
            LEFT JOIN products p ON hc.product_id = p.id
            ORDER BY hc.position ASC
        ");
        $stmt->execute();
        $carousels = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Append full URL to image for each item
        foreach ($carousels as &$carousel) {
            $carousel['image_url'] = getImageUrl($carousel['image_url']);
        }

        http_response_code(200);
        echo json_encode(['success' => true, 'carousels' => $carousels]);
        break;

    case 'POST':
        // Check if this is an UPDATE request (emulated with _method=PUT)
        $isUpdate = isset($_POST['_method']) && strtoupper($_POST['_method']) === 'PUT';

        if ($isUpdate) {
            // --- UPDATE LOGIC ---
            $id = $_POST['id'] ?? null;
            if (!$id) {
                http_response_code(400);
                echo json_encode(['success' => false, 'error' => 'Item ID is required for an update.']);
                exit;
            }

            // Get the current item to find the old image filename
            $stmt = $db->prepare("SELECT image_url FROM home_carousel WHERE id = :id");
            $stmt->execute([':id' => $id]);
            $currentItem = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$currentItem) {
                http_response_code(404);
                echo json_encode(['success' => false, 'error' => 'Item not found.']);
                exit;
            }

            // Handle potential new image upload
            $newImageName = handleImageUpload($currentItem['image_url']);

            // Securely build the UPDATE query with a whitelist of allowed fields
            $allowedFields = ['title', 'description', 'price', 'category_id', 'product_id', 'tags', 'status', 'position'];
            $updateParts = [];
            $params = [':id' => $id];

            foreach ($allowedFields as $field) {
                if (isset($_POST[$field])) {
                    $updateParts[] = "$field = :$field";
                    $value = $_POST[$field];
                    // Handle tags specifically if they are comma-separated
                    $params[":$field"] = ($field === 'tags' && is_string($value)) ? json_encode(array_map('trim', explode(',', $value))) : $value;
                }
            }

            // If a new image was uploaded, add it to the update query
            if ($newImageName) {
                $updateParts[] = "image_url = :image_url";
                $params[':image_url'] = $newImageName;
            }

            if (empty($updateParts)) {
                http_response_code(200);
                echo json_encode(['success' => true, 'message' => 'No fields to update.']);
                exit;
            }

            $sql = "UPDATE home_carousel SET " . implode(", ", $updateParts) . " WHERE id = :id";
            $stmt = $db->prepare($sql);
            
            if ($stmt->execute($params)) {
                http_response_code(200);
                echo json_encode(['success' => true, 'message' => 'Carousel item updated successfully.']);
            } else {
                http_response_code(500);
                echo json_encode(['success' => false, 'error' => 'Failed to update carousel item in the database.']);
            }

        } else {
            // --- CREATE LOGIC ---
            if (empty($_POST['title']) || empty($_FILES['image'])) {
                http_response_code(400);
                echo json_encode(['success' => false, 'error' => 'Title and image are required to create an item.']);
                exit;
            }
            
            $newImageName = handleImageUpload();
            if (!$newImageName) {
                 http_response_code(400);
                 echo json_encode(['success' => false, 'error' => 'Image upload failed or no image provided.']);
                 exit;
            }
            
            $tags = isset($_POST['tags']) ? json_encode(array_map('trim', explode(',', $_POST['tags']))) : null;

            $sql = "INSERT INTO home_carousel (title, description, image_url, price, category_id, product_id, tags, status, position)
                    VALUES (:title, :description, :image_url, :price, :category_id, :product_id, :tags, :status, :position)";
            $stmt = $db->prepare($sql);

            $stmt->execute([
                ':title'        => $_POST['title'],
                ':description'  => $_POST['description'] ?? null,
                ':image_url'    => $newImageName, // Store only the filename
                ':price'        => $_POST['price'] ?? null,
                ':category_id'  => $_POST['category_id'] ?? null,
                ':product_id'   => $_POST['product_id'] ?? null,
                ':tags'         => $tags,
                ':status'       => $_POST['status'] ?? 'inactive',
                ':position'     => $_POST['position'] ?? 0
            ]);

            http_response_code(201);
            echo json_encode(['success' => true, 'message' => 'Carousel item created successfully.', 'id' => $db->lastInsertId()]);
        }
        break;

    case 'DELETE':
        $id = $_GET['id'] ?? null;
        if (!$id) {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => 'Carousel ID is required.']);
            exit;
        }

        // First, get the image filename to delete the file later
        $stmt = $db->prepare("SELECT image_url FROM home_carousel WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $item = $stmt->fetch(PDO::FETCH_ASSOC);

        // Now, delete the item from the database
        $deleteStmt = $db->prepare("DELETE FROM home_carousel WHERE id = :id");
        if ($deleteStmt->execute([':id' => $id])) {
            // If DB deletion is successful, delete the physical file
            if ($item && !empty($item['image_url'])) {
                $filePath = UPLOAD_DIR . $item['image_url'];
                if (file_exists($filePath)) {
                    unlink($filePath);
                }
            }
            http_response_code(200);
            echo json_encode(['success' => true, 'message' => 'Carousel item deleted successfully.']);
        } else {
            http_response_code(500);
            echo json_encode(['success' => false, 'error' => 'Failed to delete carousel item from the database.']);
        }
        break;

    default:
        http_response_code(405);
        echo json_encode(['success' => false, 'error' => 'Method Not Allowed']);
        break;
}
?>