<?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';
require_once __DIR__ . '/../../core/Logger.php';

$db = Database::getInstance();

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

/**
 * ----------------------------
 * Required fields
 * ----------------------------
 */
Validator::required($_POST, [
    'title',
    'short_description',
    'description',
    'offer_price',
    'start_date',
    'end_date',
    'redirect_url'
]);

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

/**
 * ----------------------------
 * Date validation
 * ----------------------------
 */
if (strtotime($_POST['end_date']) <= strtotime($_POST['start_date'])) {
    Response::error('End date must be greater than start date', 422);
}

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

    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
 * ----------------------------
 */
$uploadDir = BASE_PATH . '/uploads/offers/';

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
 * ----------------------------
 */
if (
    !move_uploaded_file($_FILES['desktop_image']['tmp_name'], $uploadDir . $desktopFile) ||
    !move_uploaded_file($_FILES['mobile_image']['tmp_name'], $uploadDir . $mobileFile)
) {
    Response::error('Failed to move uploaded images');
}

/**
 * ----------------------------
 * Public image URLs
 * ----------------------------
 */
$desktopImagePath = BASE_URL . UPLOAD_BASE_URL . '/offers/' . $desktopFile;
$mobileImagePath  = BASE_URL . UPLOAD_BASE_URL . '/offers/' . $mobileFile;

/**
 * ----------------------------
 * Insert offer
 * ----------------------------
 */
try {
    $stmt = $db->prepare("
        INSERT INTO offers (
            title,
            short_description,
            description,
            offer_price,
            start_date,
            end_date,
            desktop_image,
            mobile_image,
            redirect_url,
            status,
            created_at
        ) VALUES (
            :title,
            :short_description,
            :description,
            :offer_price,
            :start_date,
            :end_date,
            :desktop_image,
            :mobile_image,
            :redirect_url,
            'inactive',
            NOW()
        )
    ");

    $stmt->execute([
        'title'             => trim($_POST['title']),
        'short_description' => trim($_POST['short_description']),
        'description'       => $_POST['description'],
        'offer_price'       => $_POST['offer_price'],
        'start_date'        => $_POST['start_date'],
        'end_date'          => $_POST['end_date'],
        'desktop_image'     => $desktopImagePath,
        'mobile_image'      => $mobileImagePath,
        'redirect_url'      => $_POST['redirect_url']
    ]);

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

} catch (Throwable $e) {
    Logger::error('Offer create failed', ['error' => $e->getMessage()]);
    Response::error('Failed to create offer', 500);
}

Logger::auth('Offer created', [
    'offer_id' => $offerId,
    'by'       => $_SESSION['employee_id']
]);

Response::success('Offer created successfully', [
    'offer_id' => $offerId
]);
