<?php

namespace App\Models;

use App\Core\Model;

class GalleryAlbum extends Model
{
    protected static string $table = 'iw_gallery_albums';

    // -------------------------------------------------------------------------
    // FRONTEND
    // -------------------------------------------------------------------------

    /**
     * All visible albums, ordered by sort_order.
     */
    public static function visible(): array
    {
        return static::where(['is_visible' => 1], 'sort_order', 'ASC');
    }

    /**
     * Visible albums with image count (for homepage preview).
     */
    public static function visibleWithImageCount(): array
    {
        return static::db()->fetchAll(
            "SELECT a.*, COUNT(i.id) AS image_count
             FROM iw_gallery_albums a
             LEFT JOIN iw_gallery_images i ON i.album_id = a.id
             WHERE a.is_visible = 1
             GROUP BY a.id
             ORDER BY a.sort_order ASC, a.id ASC"
        );
    }

    // -------------------------------------------------------------------------
    // ADMIN
    // -------------------------------------------------------------------------

    /**
     * All albums with image count (for admin listing).
     */
    public static function allWithImageCount(): array
    {
        return static::db()->fetchAll(
            "SELECT a.*, COUNT(i.id) AS image_count
             FROM iw_gallery_albums a
             LEFT JOIN iw_gallery_images i ON i.album_id = a.id
             GROUP BY a.id
             ORDER BY a.sort_order ASC, a.id ASC"
        );
    }

    /**
     * Compute the next sort_order value for a new album.
     */
    public static function nextSortOrder(): int
    {
        $max = static::db()->fetchColumn("SELECT MAX(sort_order) FROM iw_gallery_albums");
        return $max !== null ? ((int) $max + 1) : 0;
    }
}
