<?php
declare(strict_types=1);

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

$db = Database::getInstance();

/**
 * Validate dealer_id
 */
if (!isset($_POST['dealer_id'])) {
    Response::error('dealer_id is required', 422);
}

$dealerId = (int)$_POST['dealer_id'];

$stmt = $db->prepare("SELECT id FROM dealers WHERE id = :id");
$stmt->execute(['id' => $dealerId]);

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

/**
 * Validate file
 */
if (!isset($_FILES['image'])) {
    Response::error('Image file is required', 422);
}

$file = $_FILES['image'];

if ($file['error'] !== UPLOAD_ERR_OK) {
    Response::error('File upload failed', 400);
}

/**
 * Allowed image types
 */
$allowedTypes = [
    'image/jpeg' => 'jpg',
    'image/png'  => 'png',
    'image/webp' => 'webp'
];

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime  = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);

if (!isset($allowedTypes[$mime])) {
    Response::error('Invalid image type', 422);
}

/**
 * File size limit (2MB)
 */
if ($file['size'] > 2 * 1024 * 1024) {
    Response::error('Image exceeds 2MB limit', 422);
}

/**
 * Prepare upload directory
 */
$baseDir = __DIR__ . '/../../../uploads/dealers/' . $dealerId;

if (!is_dir($baseDir)) {
    mkdir($baseDir, 0777, true);
}

/**
 * Generate filename
 */
$extension = $allowedTypes[$mime];
$filename  = uniqid('dealer_', true) . '.' . $extension;
$filepath  = $baseDir . '/' . $filename;

/**
 * Move file
 */
if (!move_uploaded_file($file['tmp_name'], $filepath)) {
    Response::error('Failed to save image', 500);
}

/**
 * If primary image → reset existing primary
 */
$isPrimary = isset($_POST['is_primary']) && (int)$_POST['is_primary'] === 1;

if ($isPrimary) {
    $db->prepare("
        UPDATE dealer_images 
        SET is_primary = 0 
        WHERE dealer_id = :dealer_id
    ")->execute(['dealer_id' => $dealerId]);
}

/**
 * Insert image record
 */
$stmt = $db->prepare("
    INSERT INTO dealer_images (
        dealer_id,
        image_path,
        alt_text,
        caption,
        is_primary,
        sort_order,
        status,
        created_at
    ) VALUES (
        :dealer_id,
        :image_path,
        :alt_text,
        :caption,
        :is_primary,
        :sort_order,
        'Active',
        NOW()
    )
");

$stmt->execute([
    'dealer_id'  => $dealerId,
    'image_path' => '/uploads/dealers/' . $dealerId . '/' . $filename,
    'alt_text'   => $_POST['alt_text'] ?? null,
    'caption'    => $_POST['caption'] ?? null,
    'is_primary' => $isPrimary ? 1 : 0,
    'sort_order' => $_POST['sort_order'] ?? 1
]);

Logger::auth('Dealer image uploaded', [
    'dealer_id' => $dealerId,
    'file'      => $filename,
    'by'        => $_SESSION['employee_id']
]);

Response::success('Dealer image uploaded successfully');
