<?php
declare(strict_types=1);

require_once __DIR__ . '/../../security/auth_guard.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';
require_once __DIR__ . '/../../core/Validator.php';

$db = Database::getInstance();

/**
 * ----------------------------
 * Method check
 * ----------------------------
 */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Response::error('Invalid request method', 405);
}

/**
 * ----------------------------
 * Required fields
 * ----------------------------
 */
Validator::required($_POST, ['id']);

$sliderId = (int) $_POST['id'];

/**
 * ----------------------------
 * Fetch slider (image URLs)
 * ----------------------------
 */
$stmt = $db->prepare("
    SELECT desktop_image_path, mobile_image_path
    FROM home_page_sliders
    WHERE id = :id
");
$stmt->execute(['id' => $sliderId]);

$slider = $stmt->fetch();
if (!$slider) {
    Response::error('Slider not found', 404);
}

/**
 * ----------------------------
 * Delete DB record first
 * ----------------------------
 */
$stmt = $db->prepare("DELETE FROM home_page_sliders WHERE id = :id");
$stmt->execute(['id' => $sliderId]);

/**
 * ----------------------------
 * Helper: Convert URL → filesystem path
 * ----------------------------
 */
function urlToFilePath(string $url): ?string
{
    // If already relative (legacy data)
    if (!str_starts_with($url, 'http')) {
        return BASE_PATH . '/uploads/' . ltrim($url, '/');
    }

    // Remove base URL
    $relativePath = str_replace(
        rtrim(BASE_URL, '/') . rtrim(UPLOAD_BASE_URL, '/'),
        '',
        $url
    );

    return BASE_PATH . '/uploads' . $relativePath;
}

/**
 * ----------------------------
 * Delete images from disk
 * ----------------------------
 */
$desktopFile = urlToFilePath($slider['desktop_image_path']);
$mobileFile  = urlToFilePath($slider['mobile_image_path']);

if ($desktopFile && is_file($desktopFile)) {
    unlink($desktopFile);
}

if ($mobileFile && is_file($mobileFile)) {
    unlink($mobileFile);
}

/**
 * ----------------------------
 * Response
 * ----------------------------
 */
Response::success('Slider deleted successfully');
