<?php
declare(strict_types=1);

/** Parse PHP ini size (e.g. "8M", "128K") to bytes. */
function admin_ini_bytes(string $iniKey): int
{
    $v = ini_get($iniKey);
    if ($v === false || $v === '') {
        return PHP_INT_MAX;
    }
    $v = trim((string) $v);
    if (!preg_match('/^(-?\d+(?:\.\d+)?)\s*([kmg]?)$/i', $v, $m)) {
        return max(0, (int) $v);
    }
    $n = (float) $m[1];
    $u = strtoupper($m[2] ?? '');
    return match ($u) {
        'G' => (int) round($n * 1073741824),
        'M' => (int) round($n * 1048576),
        'K' => (int) round($n * 1024),
        default => (int) round($n),
    };
}

/**
 * True when POST body exceeded post_max_size: PHP clears $_POST and $_FILES (CSRF + file lost).
 */
function admin_post_body_too_large(): bool
{
    if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
        return false;
    }
    if (!empty($_POST) || !empty($_FILES)) {
        return false;
    }
    $len = (int) ($_SERVER['CONTENT_LENGTH'] ?? 0);
    if ($len < 1024) {
        return false;
    }
    $ct = (string) ($_SERVER['CONTENT_TYPE'] ?? '');
    if (stripos($ct, 'multipart/form-data') !== false) {
        return true;
    }
    return $len >= 1048576;
}

/**
 * @return string|null Relative path from site root (uploads/...) or null on failure
 */
function admin_save_upload(string $field, string $subfolder, array $allowedMime = ['image/jpeg','image/png','image/webp','image/gif']): ?string
{
    if (empty($_FILES[$field]) || $_FILES[$field]['error'] !== UPLOAD_ERR_OK) {
        return null;
    }
    $tmp = $_FILES[$field]['tmp_name'];
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = $finfo->file($tmp);
    if (!in_array($mime, $allowedMime, true)) {
        return null;
    }
    $ext = match ($mime) {
        'image/jpeg' => 'jpg',
        'image/png' => 'png',
        'image/webp' => 'webp',
        'image/gif' => 'gif',
        default => null,
    };
    if ($ext === null) {
        return null;
    }
    $dir = UPLOAD_PATH . DIRECTORY_SEPARATOR . $subfolder;
    if (!is_dir($dir)) {
        mkdir($dir, 0755, true);
    }
    $name = bin2hex(random_bytes(16)) . '.' . $ext;
    $dest = $dir . DIRECTORY_SEPARATOR . $name;
    if (!move_uploaded_file($tmp, $dest)) {
        return null;
    }
    return UPLOAD_URL . $subfolder . '/' . $name;
}

/**
 * Save MP4/WebM/OGG video upload for hero banners etc.
 *
 * @return array{ok: true, path: string}|array{ok: false, error: string}
 */
function admin_save_video_upload(string $field, string $subfolder = 'banners'): array
{
    if (empty($_FILES[$field])) {
        return ['ok' => false, 'error' => 'No file sent.'];
    }
    $err = (int)($_FILES[$field]['error'] ?? UPLOAD_ERR_NO_FILE);
    if ($err !== UPLOAD_ERR_OK) {
        $lim = ' upload_max_filesize=' . ini_get('upload_max_filesize') . ', post_max_size=' . ini_get('post_max_size') . '.';
        $msg = match ($err) {
            UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE => 'File is too large for PHP limits (' . $lim . '). Set both to at least 64M in .user.ini or php.ini, then retry.',
            UPLOAD_ERR_PARTIAL => 'Upload was interrupted.',
            UPLOAD_ERR_NO_FILE => 'No file selected.',
            default => 'Upload failed (code ' . $err . ').',
        };
        return ['ok' => false, 'error' => $msg];
    }
    $tmp = $_FILES[$field]['tmp_name'];
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = $finfo->file($tmp);
    $origLower = strtolower((string)($_FILES[$field]['name'] ?? ''));
    $mimeMap = [
        'video/mp4' => 'mp4',
        'video/webm' => 'webm',
        'video/ogg' => 'ogv',
        'application/ogg' => 'ogv',
    ];
    $ext = $mimeMap[$mime] ?? null;
    if ($ext === null) {
        if (str_ends_with($origLower, '.mp4')) {
            $ext = 'mp4';
        } elseif (str_ends_with($origLower, '.webm')) {
            $ext = 'webm';
        } elseif (str_ends_with($origLower, '.ogv') || str_ends_with($origLower, '.ogg')) {
            $ext = 'ogv';
        }
    }
    if ($ext === null) {
        return ['ok' => false, 'error' => 'Invalid video type. Use MP4 (H.264) or WebM. Detected MIME: ' . $mime];
    }
    $dir = UPLOAD_PATH . DIRECTORY_SEPARATOR . $subfolder;
    if (!is_dir($dir)) {
        mkdir($dir, 0755, true);
    }
    $fname = bin2hex(random_bytes(16)) . '.' . $ext;
    $dest = $dir . DIRECTORY_SEPARATOR . $fname;
    if (!move_uploaded_file($tmp, $dest)) {
        return ['ok' => false, 'error' => 'Could not move uploaded file to uploads folder.'];
    }
    return ['ok' => true, 'path' => UPLOAD_URL . $subfolder . '/' . $fname];
}
