<?php
/**
 * Common helper functions for admin panel
 * (CSRF functions intentionally removed)
 */

// ================== Output Sanitization ==================
function h(string $str): string {
    return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
}

// ================== Flash Messages ==================
function setFlash(string $type, string $message): void {
    $_SESSION['flash'] = ['type' => $type, 'message' => $message];
}

function getFlash(): ?array {
    if (isset($_SESSION['flash'])) {
        $flash = $_SESSION['flash'];
        unset($_SESSION['flash']);
        return $flash;
    }
    return null;
}

// ================== File Upload ==================
/**
 * Upload a single file. Returns the new filename on success,
 * null if no file was uploaded, or false on error.
 */
function uploadFile(string $inputName, array $allowedTypes, string $uploadDir): ?string {
    if (!isset($_FILES[$inputName]) || $_FILES[$inputName]['error'] !== UPLOAD_ERR_OK) {
        return null;
    }
    $file = $_FILES[$inputName];
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);
    if (!in_array($mime, $allowedTypes)) {
        setFlash('danger', 'Invalid file type.');
        return false;
    }
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $newName = uniqid('img_') . '.' . $ext;
    $dest = $uploadDir . '/' . $newName;
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    if (move_uploaded_file($file['tmp_name'], $dest)) {
        return $newName;
    }
    setFlash('danger', 'File upload failed.');
    return false;
}

/**
 * Upload multiple files. Returns an array of new filenames.
 */
function uploadMultipleFiles(string $inputName, array $allowedTypes, string $uploadDir): array {
    $uploaded = [];
    if (!isset($_FILES[$inputName]) || !is_array($_FILES[$inputName]['name'])) {
        return $uploaded;
    }
    $files = $_FILES[$inputName];
    for ($i = 0; $i < count($files['name']); $i++) {
        if ($files['error'][$i] !== UPLOAD_ERR_OK) continue;
        $tmpName = $files['tmp_name'][$i];
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime = finfo_file($finfo, $tmpName);
        finfo_close($finfo);
        if (!in_array($mime, $allowedTypes)) continue;
        $ext = pathinfo($files['name'][$i], PATHINFO_EXTENSION);
        $newName = uniqid('prod_') . '.' . $ext;
        $dest = $uploadDir . '/' . $newName;
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        if (move_uploaded_file($tmpName, $dest)) {
            $uploaded[] = $newName;
        }
    }
    return $uploaded;
}

/**
 * Delete a file if it exists.
 */
function deleteFile(string $path): void {
    if (file_exists($path)) {
        unlink($path);
    }
}