<?php
/**
 * File Upload Helper
 * Strict security checks: MIME, extension, size, randomized filename
 */

class Upload {
    private static array $allowedMimes = [
        'image/jpeg' => ['jpg', 'jpeg'],
        'image/png'  => ['png'],
        'image/webp' => ['webp']
    ];

    private static int $maxSize = 2097152; // 2 MB

    /**
     * Handle Avatar Upload
     * @return array [bool $success, string $result (filename or error message)]
     */
    public static function processAvatar(array $file, int $userId): array {
        if (!isset($file['error']) || is_array($file['error'])) {
            return [false, __('error_occurred')];
        }

        switch ($file['error']) {
            case UPLOAD_ERR_OK:
                break;
            case UPLOAD_ERR_NO_FILE:
                return [false, 'กรุณาเลือกไฟล์รูปภาพ'];
            case UPLOAD_ERR_INI_SIZE:
            case UPLOAD_ERR_FORM_SIZE:
                return [false, __('file_too_large')];
            default:
                return [false, __('error_occurred')];
        }

        // Check size
        if ($file['size'] > self::$maxSize) {
            return [false, __('file_too_large')];
        }

        // Check MIME type using finfo
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mime = $finfo->file($file['tmp_name']);

        if (!array_key_exists($mime, self::$allowedMimes)) {
            return [false, __('invalid_file_type')];
        }

        // Verify Extension
        $originalExt = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $validExts = self::$allowedMimes[$mime];

        if (!in_array($originalExt, $validExts, true)) {
            $originalExt = $validExts[0];
        }

        // Generate safe unique filename
        $newFilename = sprintf(
            'avatar_%d_%s_%s.%s',
            $userId,
            time(),
            bin2hex(random_bytes(8)),
            $originalExt
        );

        $targetDir = dirname(__DIR__, 2) . '/uploads/profiles/';
        if (!is_dir($targetDir)) {
            @mkdir($targetDir, 0777, true);
        }
        @chmod($targetDir, 0777);

        if (!is_dir($targetDir) || !is_writable($targetDir)) {
            return [false, 'ระบบไม่มีสิทธิ์เขียนไฟล์ (Permission Denied) กรุณา CHMOD 777 ให้โฟลเดอร์: ' . $targetDir];
        }

        $targetPath = $targetDir . $newFilename;

        $saved = false;
        if (is_uploaded_file($file['tmp_name'])) {
            $saved = @move_uploaded_file($file['tmp_name'], $targetPath);
        }
        if (!$saved) {
            $saved = @copy($file['tmp_name'], $targetPath);
        }
        if (!$saved) {
            $content = @file_get_contents($file['tmp_name']);
            if ($content !== false) {
                $saved = @file_put_contents($targetPath, $content) !== false;
            }
        }

        if (!$saved) {
            $err = error_get_last();
            $msg = $err ? $err['message'] : 'Unknown error';
            return [false, 'ระบบไม่สามารถเซฟไฟล์ได้ Error: ' . $msg];
        }

        return [true, $newFilename];
    }

    /**
     * Handle Store Logo & Cover Image Upload
     * @return array [bool $success, string $result (filename or error message)]
     */
    public static function processStoreImage(array $file, int $storeId, string $type = 'logo'): array {
        if (!isset($file['error']) || is_array($file['error'])) {
            return [false, __('error_occurred')];
        }

        switch ($file['error']) {
            case UPLOAD_ERR_OK:
                break;
            case UPLOAD_ERR_NO_FILE:
                return [false, 'กรุณาเลือกไฟล์รูปภาพ'];
            case UPLOAD_ERR_INI_SIZE:
            case UPLOAD_ERR_FORM_SIZE:
                return [false, __('file_too_large')];
            default:
                return [false, __('error_occurred')];
        }

        if ($file['size'] > self::$maxSize) {
            return [false, __('file_too_large')];
        }

        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mime = $finfo->file($file['tmp_name']);

        if (!array_key_exists($mime, self::$allowedMimes)) {
            return [false, __('invalid_file_type')];
        }

        $originalExt = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $validExts = self::$allowedMimes[$mime];

        if (!in_array($originalExt, $validExts, true)) {
            $originalExt = $validExts[0];
        }

        $newFilename = sprintf(
            'store_%s_%d_%s_%s.%s',
            $type,
            $storeId,
            time(),
            bin2hex(random_bytes(6)),
            $originalExt
        );

        $targetDir = dirname(__DIR__, 2) . '/uploads/stores/';
        if (!is_dir($targetDir)) {
            @mkdir($targetDir, 0777, true);
        }
        @chmod($targetDir, 0777);

        if (!is_dir($targetDir) || !is_writable($targetDir)) {
            return [false, 'ระบบไม่มีสิทธิ์เขียนไฟล์ (Permission Denied) กรุณา CHMOD 777 ให้โฟลเดอร์: ' . $targetDir];
        }

        $targetPath = $targetDir . $newFilename;

        $saved = false;
        if (is_uploaded_file($file['tmp_name'])) {
            $saved = @move_uploaded_file($file['tmp_name'], $targetPath);
        }
        if (!$saved) {
            $saved = @copy($file['tmp_name'], $targetPath);
        }
        if (!$saved) {
            $content = @file_get_contents($file['tmp_name']);
            if ($content !== false) {
                $saved = @file_put_contents($targetPath, $content) !== false;
            }
        }

        if (!$saved) {
            $err = error_get_last();
            $msg = $err ? $err['message'] : 'Unknown error';
            return [false, 'ระบบไม่สามารถเซฟไฟล์ได้ Error: ' . $msg];
        }

        return [true, $newFilename];
    }

    /**
     * Handle Product Image Upload
     * @return array [bool $success, string $result (filename or error message)]
     */
    public static function processProductImage(array $file, int $storeId): array {
        if (!isset($file['error']) || is_array($file['error'])) {
            return [false, __('error_occurred')];
        }

        switch ($file['error']) {
            case UPLOAD_ERR_OK:
                break;
            case UPLOAD_ERR_NO_FILE:
                return [false, 'กรุณาเลือกไฟล์รูปภาพ'];
            case UPLOAD_ERR_INI_SIZE:
            case UPLOAD_ERR_FORM_SIZE:
                return [false, __('file_too_large')];
            default:
                return [false, __('error_occurred')];
        }

        if ($file['size'] > self::$maxSize) {
            return [false, __('file_too_large')];
        }

        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mime = $finfo->file($file['tmp_name']);

        if (!array_key_exists($mime, self::$allowedMimes)) {
            return [false, __('invalid_file_type')];
        }

        $originalExt = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $validExts = self::$allowedMimes[$mime];

        if (!in_array($originalExt, $validExts, true)) {
            $originalExt = $validExts[0];
        }

        $newFilename = sprintf(
            'prod_%d_%s_%s.%s',
            $storeId,
            time(),
            bin2hex(random_bytes(6)),
            $originalExt
        );

        $targetDir = dirname(__DIR__, 2) . '/uploads/products/';
        if (!is_dir($targetDir)) {
            @mkdir($targetDir, 0777, true);
        }
        @chmod($targetDir, 0777);

        if (!is_dir($targetDir) || !is_writable($targetDir)) {
            return [false, 'ระบบไม่มีสิทธิ์เขียนไฟล์ (Permission Denied) กรุณา CHMOD 777 ให้โฟลเดอร์: ' . $targetDir];
        }

        $targetPath = $targetDir . $newFilename;

        $saved = false;
        if (is_uploaded_file($file['tmp_name'])) {
            $saved = @move_uploaded_file($file['tmp_name'], $targetPath);
        }
        if (!$saved) {
            $saved = @copy($file['tmp_name'], $targetPath);
        }
        if (!$saved) {
            $content = @file_get_contents($file['tmp_name']);
            if ($content !== false) {
                $saved = @file_put_contents($targetPath, $content) !== false;
            }
        }

        if (!$saved) {
            $err = error_get_last();
            $msg = $err ? $err['message'] : 'Unknown error';
            return [false, 'ระบบไม่สามารถเซฟไฟล์ได้ Error: ' . $msg];
        }

        return [true, $newFilename];
    }

    /**
     * Delete store image
     */
    public static function deleteStoreImage(?string $filename): void {
        if (!empty($filename)) {
            $path = dirname(__DIR__, 2) . '/uploads/stores/' . basename($filename);
            if (file_exists($path) && is_file($path)) {
                @unlink($path);
            }
        }
    }

    /**
     * Delete product image
     */
    public static function deleteProductImage(?string $filename): void {
        if (!empty($filename)) {
            $path = dirname(__DIR__, 2) . '/uploads/products/' . basename($filename);
            if (file_exists($path) && is_file($path)) {
                @unlink($path);
            }
        }
    }

    /**
     * Delete previous avatar if exists and not default
     */
    public static function deleteOldAvatar(?string $filename): void {
        if (!empty($filename)) {
            $path = dirname(__DIR__, 2) . '/uploads/profiles/' . basename($filename);
            if (file_exists($path) && is_file($path)) {
                @unlink($path);
            }
        }
    }
}

