<?php

declare(strict_types=1);

/**
 * 技師評論圖片上傳（儲存於 fate/uploads/reviews/）。
 */

function fate_review_image_upload_dir(): string
{
    return dirname(__DIR__) . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'reviews';
}

/** 相對路徑 → 店家頁可引用的公開 URL。 */
function fate_review_image_public_url(string $rel): string
{
    $rel = ltrim(str_replace('\\', '/', trim($rel)), '/');

    return './' . $rel;
}

/**
 * @param array<string,mixed> $file $_FILES['image']
 * @return array{ok:bool, error:?string, url:?string, rel:?string}
 */
function fate_review_image_save_uploaded_file(array $file, int $memberId): array
{
    if ($memberId <= 0) {
        return ['ok' => false, 'error' => '請先登入。', 'url' => null, 'rel' => null];
    }
    if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
        return ['ok' => false, 'error' => '上傳失敗。', 'url' => null, 'rel' => null];
    }
    $tmp = (string) ($file['tmp_name'] ?? '');
    if ($tmp === '' || !is_uploaded_file($tmp)) {
        return ['ok' => false, 'error' => '無效的上傳檔案。', 'url' => null, 'rel' => null];
    }
    if ((int) ($file['size'] ?? 0) > 5 * 1024 * 1024) {
        return ['ok' => false, 'error' => '圖片請小於 5MB。', 'url' => null, 'rel' => null];
    }

    $bytes = @file_get_contents($tmp);
    if ($bytes === false || $bytes === '') {
        return ['ok' => false, 'error' => '無法讀取圖片。', 'url' => null, 'rel' => null];
    }

    if (!function_exists('imagecreatefromstring')) {
        return ['ok' => false, 'error' => '伺服器未啟用 GD，無法處理圖片。', 'url' => null, 'rel' => null];
    }

    $srcImg = @imagecreatefromstring($bytes);
    if ($srcImg === false) {
        return ['ok' => false, 'error' => '不支援的圖片格式。', 'url' => null, 'rel' => null];
    }

    $sw = imagesx($srcImg);
    $sh = imagesy($srcImg);
    if ($sw < 1 || $sh < 1) {
        imagedestroy($srcImg);

        return ['ok' => false, 'error' => '圖片尺寸無效。', 'url' => null, 'rel' => null];
    }

    $maxW = 1920;
    $outImg = $srcImg;
    if ($sw > $maxW) {
        $nh = (int) max(1, round($sh * ($maxW / $sw)));
        $resized = imagecreatetruecolor($maxW, $nh);
        if ($resized === false) {
            imagedestroy($srcImg);

            return ['ok' => false, 'error' => '無法處理圖片。', 'url' => null, 'rel' => null];
        }
        imagecopyresampled($resized, $srcImg, 0, 0, 0, 0, $maxW, $nh, $sw, $sh);
        imagedestroy($srcImg);
        $outImg = $resized;
    }

    $dir = fate_review_image_upload_dir();
    if (!is_dir($dir) && !@mkdir($dir, 0775, true) && !is_dir($dir)) {
        imagedestroy($outImg);

        return ['ok' => false, 'error' => '無法建立上傳目錄。', 'url' => null, 'rel' => null];
    }

    $basename = 'm' . $memberId . '_' . time() . '_' . bin2hex(random_bytes(4)) . '.jpg';
    $destFs = $dir . DIRECTORY_SEPARATOR . $basename;
    $rel = 'uploads/reviews/' . $basename;

    if (!imagejpeg($outImg, $destFs, 88)) {
        imagedestroy($outImg);

        return ['ok' => false, 'error' => '無法儲存圖片。', 'url' => null, 'rel' => null];
    }
    imagedestroy($outImg);

    return [
        'ok' => true,
        'error' => null,
        'rel' => $rel,
        'url' => fate_review_image_public_url($rel),
    ];
}
