<?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, ['priority']);

if (
    empty($_FILES['desktop_image']['tmp_name']) ||
    empty($_FILES['mobile_image']['tmp_name'])
) {
    Response::error('Desktop and mobile images are required', 422);
}

/**
 * ----------------------------
 * Image validation
 * ----------------------------
 */
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');
    }
}

validateImage($_FILES['desktop_image']);
validateImage($_FILES['mobile_image']);

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

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

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

/**
 * ----------------------------
 * Generate filenames
 * ----------------------------
 */
$desktopFile = 'desktop_' . uniqid('', true) . '.webp';
$mobileFile  = 'mobile_' . uniqid('', true) . '.webp';

/**
 * ----------------------------
 * Move uploaded files
 * ----------------------------
 */
$desktopMoved = move_uploaded_file(
    $_FILES['desktop_image']['tmp_name'],
    $uploadDir . $desktopFile
);

$mobileMoved = move_uploaded_file(
    $_FILES['mobile_image']['tmp_name'],
    $uploadDir . $mobileFile
);

if (!$desktopMoved || !$mobileMoved) {
    Response::error('Failed to move uploaded images');
}

/**
 * ----------------------------
 * 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;
$createdBy = (int) $_SESSION['employee_id'];

/**
 * ----------------------------
 * Public URLs (UPLOAD_BASE_URL)
 * ----------------------------
 */
$desktopImagePath = BASE_URL . UPLOAD_BASE_URL . '/sliders/home/' . $desktopFile;
$mobileImagePath  = BASE_URL . UPLOAD_BASE_URL . '/sliders/home/' . $mobileFile;


/**
 * ----------------------------
 * Insert slider
 * ----------------------------
 */
$stmt = $db->prepare("
    INSERT INTO home_page_sliders (
        title,
        subtitle,
        desktop_image_path,
        mobile_image_path,
        priority,
        link_url,
        link_text,
        is_active,
        start_date,
        end_date,
        created_by,
        created_at
    ) VALUES (
        :title,
        :subtitle,
        :desktop_image,
        :mobile_image,
        :priority,
        :link_url,
        :link_text,
        :is_active,
        :start_date,
        :end_date,
        :created_by,
        NOW()
    )
");

$stmt->execute([
    'title'         => $title,
    'subtitle'      => $subtitle,
    'desktop_image' => $desktopImagePath,
    'mobile_image'  => $mobileImagePath,
    'priority'      => $priority,
    'link_url'      => $linkUrl,
    'link_text'     => $linkText,
    'is_active'     => $isActive,
    'start_date'    => $startDate,
    'end_date'      => $endDate,
    'created_by'    => $createdBy
]);

$sliderId = (int) $db->lastInsertId();

/**
 * ----------------------------
 * Response
 * ----------------------------
 */
Response::success('Slider created successfully', [
    'slider_id' => $sliderId
]);
