<?php

namespace App\Core;

class Upload
{
    private const ALLOWED = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'];
    private const MAX_SIZE = 2 * 1024 * 1024; // 2MB

    /**
     * Simpan file upload ke public/uploads/{folder}/, kembalikan nama file baru atau null kalau tidak ada file/gagal.
     * $error diisi pesan kesalahan kalau validasi gagal.
     */
    public static function image(array $file, string $folder, ?string &$error = null): ?string
    {
        if (empty($file['name']) || $file['error'] === UPLOAD_ERR_NO_FILE) {
            return null; // tidak ada file diupload, bukan error
        }

        if ($file['error'] !== UPLOAD_ERR_OK) {
            $error = 'Upload gagal (kode error: ' . $file['error'] . ').';
            return null;
        }

        if ($file['size'] > self::MAX_SIZE) {
            $error = 'Ukuran file maksimal 2MB.';
            return null;
        }

        $mime = mime_content_type($file['tmp_name']);
        if (!isset(self::ALLOWED[$mime])) {
            $error = 'Format file harus JPG, PNG, atau WEBP.';
            return null;
        }

        $ext = self::ALLOWED[$mime];
        $filename = date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
        $targetDir = BASE_PATH . '/public/uploads/' . $folder;

        if (!is_dir($targetDir)) {
            mkdir($targetDir, 0755, true);
        }

        if (!move_uploaded_file($file['tmp_name'], $targetDir . '/' . $filename)) {
            $error = 'Gagal menyimpan file ke server.';
            return null;
        }

        return $filename;
    }

    /**
     * Simpan banyak file sekaligus (dari input type=file name="foto[]" multiple).
     * Mengembalikan array nama file yang berhasil disimpan. File yang gagal validasi dilewati saja.
     */
    public static function imageMultiple(array $files, string $folder): array
    {
        $saved = [];

        if (empty($files['name']) || !is_array($files['name'])) {
            return $saved;
        }

        $count = count($files['name']);

        for ($i = 0; $i < $count; $i++) {
            if ($files['error'][$i] === UPLOAD_ERR_NO_FILE) {
                continue;
            }

            $single = [
                'name'     => $files['name'][$i],
                'type'     => $files['type'][$i],
                'tmp_name' => $files['tmp_name'][$i],
                'error'    => $files['error'][$i],
                'size'     => $files['size'][$i],
            ];

            $error = null;
            $filename = self::image($single, $folder, $error);

            if ($filename) {
                $saved[] = $filename;
            }
        }

        return $saved;
    }

    public static function delete(string $folder, ?string $filename): void
    {
        if (!$filename) {
            return;
        }

        $path = BASE_PATH . '/public/uploads/' . $folder . '/' . $filename;
        if (is_file($path)) {
            unlink($path);
        }
    }
}
