<?php
declare(strict_types=1);

// Absolute path to the shared "Project imgs" directory.
function project_media_base_path(): string
{
    return dirname(__DIR__) . DIRECTORY_SEPARATOR . 'Project imgs';
}

// Compute a safe folder name for a project.
function project_media_folder(array $project): string
{
    $slug = trim((string)($project['slug'] ?? ''));
    if ($slug !== '' && preg_match('/^[a-zA-Z0-9-]+$/', $slug)) {
        return strtolower($slug);
    }

    $title = trim((string)($project['title'] ?? ''));
    if ($title !== '') {
        $folder = strtolower((string)preg_replace('/[^a-z0-9]+/i', '-', $title));
        $folder = trim($folder, '-');
        if ($folder !== '') return $folder;
    }

    if (!empty($project['id'])) {
        return 'project-' . (int)$project['id'];
    }

    return 'project-media';
}


// Return the full filesystem path for the project's media directory.
function project_media_dir(array $project): string
{
    $dir = project_media_base_path() . DIRECTORY_SEPARATOR . project_media_folder($project);
    if (!is_dir($dir)) {
        @mkdir($dir, 0755, true);
    }
    return $dir;
}


// Build a public URL for a stored media file.

function project_media_url(string $folder, string $filename): string
{
    $base = '/Project%20imgs';
    return url_path($base . '/' . rawurlencode($folder) . '/' . rawurlencode($filename));
}

// Return a list of image URLs for a project (sorted newest first).
function project_media_files(array $project): array
{
    $folder = project_media_folder($project);
    $dir = project_media_base_path() . DIRECTORY_SEPARATOR . $folder;
    if (!is_dir($dir)) return [];
    $files = [];
    foreach (glob($dir . DIRECTORY_SEPARATOR . '*.{jpg,jpeg,png,webp}', GLOB_BRACE) ?: [] as $path) {
        if (!is_file($path)) continue;
        $stat = @stat($path) ?: [];
        $files[] = [
            'url'      => project_media_url($folder, basename($path)),
            'modified' => (int)($stat['mtime'] ?? 0),
        ];
    }

    usort($files, fn($a, $b) => ($b['modified'] ?? 0) <=> ($a['modified'] ?? 0));
    return array_values(array_map(fn($f) => (string)$f['url'], $files));
}

// Slugify a string to lower-case letters/numbers/hyphens.
function project_slugify(string $value): string
{
    $value = trim($value);
    $value = preg_replace('/[^a-z0-9]+/i', '-', $value) ?? '';
    $value = trim($value, '-');
    $value = function_exists('mb_strtolower') ? mb_strtolower($value) : strtolower($value);
    return $value;
}
