<?php

final class Uploads
{
    public static function dir(): string
    {
        $d = (string) Config::get('upload_dir');
        if (!is_dir($d) && !@mkdir($d, 0750, true)) {
            throw new ApiError('תיקיית הקבצים אינה זמינה לכתיבה', 500);
        }
        return rtrim($d, '/');
    }

    public static function allowedExtensions(): array
    {
        $img = array_filter(array_map('trim', explode(',', (string) Config::setting('allowed_image_types', ''))));
        $vid = array_filter(array_map('trim', explode(',', (string) Config::setting('allowed_video_types', ''))));
        return ['image' => $img, 'video' => $vid];
    }

    /** ini value like "8M" as bytes. */
    private static function iniBytes(string $value): int
    {
        $value = trim($value);
        if ($value === '') {
            return 0;
        }
        $unit = strtolower($value[strlen($value) - 1]);
        $num  = (int) $value;
        return match ($unit) {
            'g' => $num * 1024 * 1024 * 1024,
            'm' => $num * 1024 * 1024,
            'k' => $num * 1024,
            default => $num,
        };
    }

    /**
     * When a request is larger than post_max_size, PHP silently discards the
     * whole body — $_FILES and $_POST arrive empty and the upload looks like
     * "no file chosen". Detect it and say what actually happened.
     */
    public static function assertRequestFits(): void
    {
        $len = (int) ($_SERVER['CONTENT_LENGTH'] ?? 0);
        $max = self::iniBytes((string) ini_get('post_max_size'));
        if ($max > 0 && $len > $max) {
            $mb = round($len / 1048576, 1);
            throw new ApiError(
                "הקובץ ({$mb} MB) חורג מהמגבלה בשרת (post_max_size = " . ini_get('post_max_size') . "). "
                . 'יש להגדיל את upload_max_filesize ו-post_max_size בהגדרות PHP.', 413);
        }
    }

    public static function allowedDocExtensions(): array
    {
        return array_filter(array_map('trim', explode(',', (string) Config::setting('allowed_doc_types', ''))));
    }

    /**
     * Stores a document (pdf, word, excel and so on) under docs/YYYY/MM.
     * Documents are validated by extension rather than MIME, because Office
     * formats report a handful of different types depending on the client.
     */
    public static function storeDocument(array $file): array
    {
        if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
            throw new ApiError(self::errorText((int) ($file['error'] ?? 0)), 400);
        }
        $maxMb = (int) Config::setting('max_upload_mb', '200');
        if ($file['size'] > $maxMb * 1024 * 1024) {
            throw new ApiError("הקובץ גדול מהמותר ({$maxMb} MB)", 400);
        }

        $original = (string) $file['name'];
        $ext      = strtolower(pathinfo($original, PATHINFO_EXTENSION));
        $allowed  = array_merge(self::allowedDocExtensions(), self::allowedExtensions()['image']);
        if ($ext === '' || !in_array($ext, $allowed, true)) {
            throw new ApiError('סוג קובץ זה אינו מותר להעלאה', 400);
        }
        // Never accept anything the web server might decide to execute.
        if (preg_match('/^(php\d?|phtml|phar|cgi|pl|py|sh|exe|bat|js|html?)$/i', $ext)) {
            throw new ApiError('סוג קובץ זה אינו מותר להעלאה', 400);
        }

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

        $rel = 'docs/' . date('Y/m');
        $abs = self::dir() . '/' . $rel;
        if (!is_dir($abs) && !@mkdir($abs, 0750, true)) {
            throw new ApiError('לא ניתן ליצור תיקייה לקובץ', 500);
        }
        $stored = bin2hex(random_bytes(16)) . '.' . $ext;
        if (!move_uploaded_file($file['tmp_name'], $abs . '/' . $stored)) {
            throw new ApiError('שמירת הקובץ נכשלה', 500);
        }
        @chmod($abs . '/' . $stored, 0640);

        return [
            'original_name' => mb_substr($original, 0, 255),
            'stored_name'   => $stored,
            'rel_path'      => $rel,
            'mime_type'     => $mime !== '' ? $mime : 'application/octet-stream',
            'size_bytes'    => (int) $file['size'],
        ];
    }

    public static function kindFor(string $ext): ?string
    {
        $a = self::allowedExtensions();
        if (in_array($ext, $a['image'], true)) {
            return 'image';
        }
        if (in_array($ext, $a['video'], true)) {
            return 'video';
        }
        return null;
    }

    /**
     * Stores one uploaded file under uploads/YYYY/MM/<ticket>/ with a random name.
     * @return array<string,mixed> row data for ticket_attachments
     */
    public static function store(array $file, int $ticketId): array
    {
        if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
            throw new ApiError(self::errorText((int) ($file['error'] ?? 0)), 400);
        }
        $maxMb = (int) Config::setting('max_upload_mb', '200');
        if ($file['size'] > $maxMb * 1024 * 1024) {
            throw new ApiError("הקובץ גדול מהמותר ({$maxMb} MB)", 400);
        }

        $original = (string) $file['name'];
        $ext      = strtolower(pathinfo($original, PATHINFO_EXTENSION));
        $kind     = self::kindFor($ext);
        if ($kind === null) {
            throw new ApiError('סוג קובץ זה אינו נתמך', 400);
        }

        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mime  = (string) $finfo->file($file['tmp_name']);
        if (!str_starts_with($mime, 'image/') && !str_starts_with($mime, 'video/')) {
            throw new ApiError('תוכן הקובץ אינו תמונה או וידאו', 400);
        }

        $rel = date('Y/m') . '/' . $ticketId;
        $abs = self::dir() . '/' . $rel;
        if (!is_dir($abs) && !@mkdir($abs, 0750, true)) {
            throw new ApiError('לא ניתן ליצור תיקייה לקובץ', 500);
        }

        $stored = bin2hex(random_bytes(16)) . '.' . $ext;
        if (!move_uploaded_file($file['tmp_name'], $abs . '/' . $stored)) {
            throw new ApiError('שמירת הקובץ נכשלה', 500);
        }
        @chmod($abs . '/' . $stored, 0640);

        return [
            'original_name' => mb_substr($original, 0, 255),
            'stored_name'   => $stored,
            'rel_path'      => $rel,
            'mime_type'     => $mime,
            'size_bytes'    => (int) $file['size'],
            'kind'          => $kind,
        ];
    }

    /** Sends the file to the browser, preferring mod_xsendfile for range support. */
    public static function serve(array $attachment): void
    {
        $path = self::dir() . '/' . $attachment['rel_path'] . '/' . $attachment['stored_name'];
        if (!is_file($path)) {
            throw new ApiError('הקובץ לא נמצא', 404);
        }
        $name   = rawurlencode($attachment['original_name']);
        $mime   = $attachment['mime_type'];
        // Only media and PDF open in the browser; everything else downloads,
        // so no uploaded file can ever be rendered as a page.
        $inline = str_starts_with($mime, 'image/') || str_starts_with($mime, 'video/')
               || $mime === 'application/pdf';
        header('Content-Type: ' . $mime);
        header(($inline ? 'Content-Disposition: inline' : 'Content-Disposition: attachment')
               . "; filename*=UTF-8''{$name}");
        header('X-Content-Type-Options: nosniff');

        if (Config::get('use_xsendfile', true)) {
            header('X-Sendfile: ' . $path);
            exit;
        }
        header('Content-Length: ' . filesize($path));
        header('Accept-Ranges: bytes');
        readfile($path);
        exit;
    }

    /** Normalises PHP's $_FILES into a flat list, whether one file or many. */
    public static function normalise(string $field): array
    {
        if (!isset($_FILES[$field])) {
            return [];
        }
        $f = $_FILES[$field];
        if (!is_array($f['name'])) {
            return [$f];
        }
        $out = [];
        foreach (array_keys($f['name']) as $i) {
            $out[] = [
                'name'     => $f['name'][$i],
                'type'     => $f['type'][$i],
                'tmp_name' => $f['tmp_name'][$i],
                'error'    => $f['error'][$i],
                'size'     => $f['size'][$i],
            ];
        }
        return $out;
    }

    private static function errorText(int $code): string
    {
        return match ($code) {
            UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE => 'הקובץ חורג מהגודל המותר בשרת',
            UPLOAD_ERR_PARTIAL   => 'ההעלאה הופסקה באמצע',
            UPLOAD_ERR_NO_FILE   => 'לא נבחר קובץ',
            UPLOAD_ERR_NO_TMP_DIR, UPLOAD_ERR_CANT_WRITE => 'שגיאת כתיבה זמנית בשרת',
            default              => 'העלאת הקובץ נכשלה',
        };
    }
}
