<?php
declare(strict_types=1);

function ensure_car_profile_columns(mysqli $conn): void
{
    static $checked = false;

    if ($checked) {
        return;
    }

    $checked = true;

    $columns = array(
        'profile_image_path' => "ALTER TABLE cars ADD COLUMN profile_image_path VARCHAR(255) NULL AFTER color",
        'profile_image_name' => "ALTER TABLE cars ADD COLUMN profile_image_name VARCHAR(255) NULL AFTER profile_image_path",
        'profile_image_mime_type' => "ALTER TABLE cars ADD COLUMN profile_image_mime_type VARCHAR(100) NULL AFTER profile_image_name",
        'profile_image_uploaded_at' => "ALTER TABLE cars ADD COLUMN profile_image_uploaded_at DATETIME NULL AFTER profile_image_mime_type",
    );

    foreach ($columns as $columnName => $alterSql) {
        $columnResult = $conn->query("SHOW COLUMNS FROM cars LIKE '" . $conn->real_escape_string($columnName) . "'");

        if (!($columnResult instanceof mysqli_result) || $columnResult->num_rows === 0) {
            if (!$conn->query($alterSql)) {
                throw new RuntimeException('Cannot add ' . $columnName . ' column: ' . $conn->error);
            }
        }
    }
}

function car_profile_upload_accept_attribute(): string
{
    return '.jpg,.jpeg,.png,.webp,image/jpeg,image/png,image/webp';
}

function car_profile_uploaded_file_from_request(string $baseName): ?array
{
    foreach (array($baseName . '_camera', $baseName . '_file', $baseName) as $fieldName) {
        $file = $_FILES[$fieldName] ?? null;

        if (!is_array($file)) {
            continue;
        }

        if ((int) ($file['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) {
            continue;
        }

        return $file;
    }

    return null;
}

function car_profile_image_url(array $row): string
{
    foreach (array('profileImageUrl', 'profile_image_path', 'car_profile_image_path') as $key) {
        $value = trim((string) ($row[$key] ?? ''));
        if ($value !== '') {
            return $value;
        }
    }

    return '';
}

function car_profile_image_name(array $row): string
{
    foreach (array('profileImageName', 'profile_image_name', 'car_profile_image_name') as $key) {
        $value = trim((string) ($row[$key] ?? ''));
        if ($value !== '') {
            return $value;
        }
    }

    return localized_text_value('รูปรถ', 'Vehicle photo');
}

function car_profile_photo_alt_text(array $row): string
{
    $plateNumber = trim((string) ($row['plate_number'] ?? $row['plateNumber'] ?? ''));
    $brandModel = trim((string) (($row['brand'] ?? '') . ' ' . ($row['model'] ?? '')));

    if ($plateNumber !== '' && $brandModel !== '') {
        return $brandModel . ' / ' . $plateNumber;
    }

    if ($plateNumber !== '') {
        return localized_text_value('รูปรถทะเบียน ', 'Vehicle photo ') . $plateNumber;
    }

    return car_profile_image_name($row);
}

function car_profile_photo_html(
    array $row,
    string $imageClass = 'vehicle-profile-photo',
    string $placeholderClass = 'vehicle-profile-photo-placeholder'
): string {
    $imageUrl = car_profile_image_url($row);

    if ($imageUrl !== '') {
        $imageAlt = car_profile_photo_alt_text($row);
        $photoTitle = localized_text_value('รูปโปรไฟล์รถ', 'Vehicle profile photo');
        $expandLabel = localized_text_value('คลิกที่รูปเพื่อดูขนาดใหญ่', 'Click photo to view a larger image');

        return '<img class="' . e($imageClass) . '"'
            . ' src="' . e($imageUrl) . '"'
            . ' alt="' . e($imageAlt) . '"'
            . ' loading="lazy"'
            . ' data-profile-photo-expand'
            . ' data-photo-src="' . e($imageUrl) . '"'
            . ' data-photo-alt="' . e($imageAlt) . '"'
            . ' data-photo-title="' . e($photoTitle) . '"'
            . ' tabindex="0"'
            . ' role="button"'
            . ' aria-label="' . e($expandLabel) . '"'
            . '>';
    }

    return '<span class="' . e($placeholderClass) . '" role="img" aria-label="' . e(localized_text_value('ยังไม่มีรูปรถ', 'No vehicle photo')) . '">'
        . app_button_icon_svg('plus-square')
        . '</span>';
}

function store_car_profile_upload(?array $photoFile, string $filePrefix = 'car-profile'): ?array
{
    if (!is_array($photoFile)) {
        return null;
    }

    $uploadError = (int) ($photoFile['error'] ?? UPLOAD_ERR_NO_FILE);
    if ($uploadError === UPLOAD_ERR_NO_FILE) {
        return null;
    }

    if ($uploadError !== UPLOAD_ERR_OK) {
        throw new RuntimeException(localized_text_value('อัปโหลดรูปรถไม่สำเร็จ', 'Vehicle photo upload failed.'));
    }

    $tmpName = trim((string) ($photoFile['tmp_name'] ?? ''));
    if ($tmpName === '' || !is_uploaded_file($tmpName)) {
        throw new RuntimeException(localized_text_value('ไฟล์รูปรถไม่ถูกต้อง', 'Vehicle photo upload is invalid.'));
    }

    $maxFileSize = 8 * 1024 * 1024;
    if ((int) ($photoFile['size'] ?? 0) > $maxFileSize) {
        throw new RuntimeException(localized_text_value('ไฟล์รูปรถต้องมีขนาดไม่เกิน 8 MB', 'Vehicle photo must be 8 MB or smaller.'));
    }

    $mimeType = '';
    if (function_exists('finfo_open')) {
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $detectedMimeType = $finfo ? finfo_file($finfo, $tmpName) : false;
        if ($finfo) {
            finfo_close($finfo);
        }
        $mimeType = is_string($detectedMimeType) ? trim($detectedMimeType) : '';
    }

    if ($mimeType === '') {
        $imageInfo = @getimagesize($tmpName);
        if (is_array($imageInfo)) {
            $mimeType = trim((string) ($imageInfo['mime'] ?? ''));
        }
    }

    $allowedMimeTypes = array(
        'image/jpeg' => 'jpg',
        'image/png' => 'png',
        'image/webp' => 'webp',
    );

    if (!array_key_exists($mimeType, $allowedMimeTypes)) {
        throw new RuntimeException(localized_text_value('รองรับเฉพาะไฟล์ JPG, PNG หรือ WEBP สำหรับรูปรถ', 'Only JPG, PNG or WEBP files are allowed for vehicle photos.'));
    }

    $targetDirectory = storage_upload_directory('car_profiles');
    if (!is_dir($targetDirectory) && !mkdir($targetDirectory, 0777, true) && !is_dir($targetDirectory)) {
        throw new RuntimeException(localized_text_value('ไม่สามารถสร้างโฟลเดอร์เก็บรูปรถได้', 'Vehicle photo directory could not be created.'));
    }

    $normalizedPrefix = strtolower((string) preg_replace('/[^a-z0-9]+/i', '-', trim($filePrefix)));
    $normalizedPrefix = trim($normalizedPrefix, '-');
    if ($normalizedPrefix === '') {
        $normalizedPrefix = 'car-profile';
    }

    try {
        $randomSuffix = bin2hex(random_bytes(4));
    } catch (Throwable $exception) {
        $randomSuffix = substr(md5(uniqid('', true)), 0, 8);
    }

    $storedFileName = $normalizedPrefix . '-' . date('YmdHis') . '-' . $randomSuffix . '.' . $allowedMimeTypes[$mimeType];
    $absolutePath = $targetDirectory . '/' . $storedFileName;

    if (!move_uploaded_file($tmpName, $absolutePath)) {
        throw new RuntimeException(localized_text_value('ไม่สามารถบันทึกรูปรถได้', 'Vehicle photo could not be saved.'));
    }

    $originalFileName = trim((string) ($photoFile['name'] ?? ''));
    if ($originalFileName === '') {
        $originalFileName = $storedFileName;
    }

    return array(
        'file_path' => storage_upload_public_prefix('car_profiles') . $storedFileName,
        'file_name' => $originalFileName,
        'mime_type' => $mimeType,
        'uploaded_at' => date('Y-m-d H:i:s'),
        'absolute_path' => $absolutePath,
    );
}

function delete_car_profile_file(?string $publicPath): void
{
    $absolutePath = storage_upload_absolute_path_from_public((string) $publicPath, 'car_profiles');

    if ($absolutePath && is_file($absolutePath)) {
        @unlink($absolutePath);
    }
}
