<?php

namespace App\Models;

use App\Core\Model;

/**
 * ITSWEBER CMS – MediaFolder Model
 *
 * Lightweight folder hierarchy for the central media manager.
 * In v1 the UI treats all folders as flat (parent_id = NULL),
 * but the schema supports one level of nesting for future use.
 */
class MediaFolder extends Model
{
    protected static string $table = 'iw_media_folders';

    /**
     * Get all folders with their media count.
     */
    public static function allWithCount(): array
    {
        return static::db()->fetchAll("
            SELECT f.*, COUNT(m.id) AS media_count
            FROM   iw_media_folders f
            LEFT JOIN iw_media m ON m.folder_id = f.id
            GROUP BY f.id
            ORDER BY f.sort_order ASC, f.name ASC
        ");
    }

    /**
     * Check if a slug already exists (for uniqueness enforcement).
     *
     * @param string   $slug      The slug to check.
     * @param int|null $excludeId Optionally exclude a specific folder ID (for updates).
     */
    public static function slugExists(string $slug, ?int $excludeId = null): bool
    {
        if ($excludeId !== null) {
            $row = static::db()->fetch(
                "SELECT id FROM iw_media_folders WHERE slug = :slug AND id != :id LIMIT 1",
                ['slug' => $slug, 'id' => $excludeId]
            );
        } else {
            $row = static::db()->fetch(
                "SELECT id FROM iw_media_folders WHERE slug = :slug LIMIT 1",
                ['slug' => $slug]
            );
        }

        return !empty($row);
    }
}
