<?php
declare(strict_types=1);

function store_payment_slip_upload(?array $slipFile, string $filePrefix = 'payment-slip'): ?array
{
    if (!is_array($slipFile)) {
        return null;
    }

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

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

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

    $maxFileSize = 5 * 1024 * 1024;
    if ((int) ($slipFile['size'] ?? 0) > $maxFileSize) {
        throw new RuntimeException(localized_text_value('ไฟล์สลิปต้องมีขนาดไม่เกิน 5 MB', 'Payment slip file must be 5 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'] ?? ''));
        }
    }

    if ($mimeType === '') {
        $extension = strtolower((string) pathinfo((string) ($slipFile['name'] ?? ''), PATHINFO_EXTENSION));
        if ($extension === 'pdf') {
            $mimeType = 'application/pdf';
        }
    }

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

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

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

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

    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('ไม่สามารถบันทึกไฟล์สลิปได้', 'Payment slip file could not be saved.'));
    }

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

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

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

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