<?php
declare(strict_types=1);

require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../security/auth_guard.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', 'priority']);

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

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

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

/**
 * ----------------------------
 * Image validation helper
 * ----------------------------
 */
function validateImage(array $file): void
{
    if ($file['error'] !== UPLOAD_ERR_OK) {
        Response::error('Image upload failed (code ' . $file['error'] . ')');
    }

    if ($file['size'] > MAX_IMAGE_SIZE) {
        Response::error('Image size exceeds limit');
    }

    $mime = mime_content_type($file['tmp_name']);
    if (!in_array($mime, ALLOWED_IMAGE_TYPES, true)) {
        Response::error('Invalid image type');
    }
}

/**
 * ----------------------------
 * Existing paths (default)
 * ----------------------------
 */
$desktopPath = $existing['desktop_image_path'];
$mobilePath  = $existing['mobile_image_path'];

/**
 * ----------------------------
 * Upload directory (FILESYSTEM)
 * ----------------------------
 */
$uploadDir = BASE_PATH . '/uploads/sliders/home/';

if (!is_dir($uploadDir) && !mkdir($uploadDir, 0775, true)) {
    Response::error('Failed to create upload directory');
}

if (!is_writable($uploadDir)) {
    Response::error('Upload directory is not writable');
}

/**
 * ----------------------------
 * Handle desktop image update
 * ----------------------------
 */
if (!empty($_FILES['desktop_image']['tmp_name'])) {
    validateImage($_FILES['desktop_image']);

    $desktopFile = 'desktop_' . uniqid('', true) . '.webp';

    if (!move_uploaded_file(
        $_FILES['desktop_image']['tmp_name'],
        $uploadDir . $desktopFile
    )) {
        Response::error('Failed to upload desktop image');
    }

    $desktopPath = BASE_URL . UPLOAD_BASE_URL . '/sliders/home/' . $desktopFile;
}

/**
 * ----------------------------
 * Handle mobile image update
 * ----------------------------
 */
if (!empty($_FILES['mobile_image']['tmp_name'])) {
    validateImage($_FILES['mobile_image']);

    $mobileFile = 'mobile_' . uniqid('', true) . '.webp';

    if (!move_uploaded_file(
        $_FILES['mobile_image']['tmp_name'],
        $uploadDir . $mobileFile
    )) {
        Response::error('Failed to upload mobile image');
    }

    $mobilePath = BASE_URL . UPLOAD_BASE_URL . '/sliders/home/' . $mobileFile;
}

/**
 * ----------------------------
 * Prepare data
 * ----------------------------
 */
$title     = trim($_POST['title'] ?? null);
$subtitle  = trim($_POST['subtitle'] ?? null);
$priority  = (int) $_POST['priority'];
$linkUrl   = $_POST['link_url'] ?? null;
$linkText  = $_POST['link_text'] ?? null;
$isActive  = (int) ($_POST['is_active'] ?? 1);
$startDate = $_POST['start_date'] ?? null;
$endDate   = $_POST['end_date'] ?? null;

/**
 * ----------------------------
 * Update slider
 * ----------------------------
 */
$stmt = $db->prepare("
    UPDATE home_page_sliders SET
        title = :title,
        subtitle = :subtitle,
        desktop_image_path = :desktop_image,
        mobile_image_path = :mobile_image,
        priority = :priority,
        link_url = :link_url,
        link_text = :link_text,
        is_active = :is_active,
        start_date = :start_date,
        end_date = :end_date,
        updated_at = NOW()
    WHERE id = :id
");

$stmt->execute([
    'id'            => $sliderId,
    'title'         => $title,
    'subtitle'      => $subtitle,
    'desktop_image' => $desktopPath,
    'mobile_image'  => $mobilePath,
    'priority'      => $priority,
    'link_url'      => $linkUrl,
    'link_text'     => $linkText,
    'is_active'     => $isActive,
    'start_date'    => $startDate,
    'end_date'      => $endDate
]);

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