<?php

namespace App\Models;

use App\Core\Model;

class GalleryImage extends Model
{
    protected static string $table = 'iw_gallery_images';

    // -------------------------------------------------------------------------
    // FRONTEND / SHARED
    // -------------------------------------------------------------------------

    /**
     * All images for an album, ordered by sort_order.
     * Includes media-related info if media_id is set (Phase 2.2).
     */
    public static function byAlbum(int $albumId): array
    {
        return static::db()->fetchAll(
            "SELECT gi.*, m.file_path AS media_file_path, m.title AS media_title, m.alt_text AS media_alt_text
             FROM iw_gallery_images gi
             LEFT JOIN iw_media m ON m.id = gi.media_id
             WHERE gi.album_id = :album_id
             ORDER BY gi.sort_order ASC",
            ['album_id' => $albumId]
        );
    }

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

    /**
     * All images for an album (admin version – enriched with media data, Phase 2.2).
     */
    public static function byAlbumForAdmin(int $albumId): array
    {
        return static::db()->fetchAll(
            "SELECT gi.*, m.file_path AS media_file_path, m.title AS media_title, m.alt_text AS media_alt_text
             FROM iw_gallery_images gi
             LEFT JOIN iw_media m ON m.id = gi.media_id
             WHERE gi.album_id = :album_id
             ORDER BY gi.sort_order ASC",
            ['album_id' => $albumId]
        );
    }

    /**
     * Compute the next sort_order value for a new image in a given album.
     */
    public static function nextSortOrder(int $albumId): int
    {
        $max = static::db()->fetchColumn(
            "SELECT MAX(sort_order) FROM iw_gallery_images WHERE album_id = :album_id",
            ['album_id' => $albumId]
        );
        return $max !== null ? ((int) $max + 1) : 0;
    }

    /**
     * Resolve the effective file_path for display/rendering.
     * If media_id is set, use the media's file_path; otherwise use the gallery_image's file_path.
     * (Phase 2.2: supports both legacy files and media references)
     */
    public static function effectiveFilePath(array $image): ?string
    {
        if (!empty($image['media_id']) && !empty($image['media_file_path'])) {
            return $image['media_file_path'];
        }
        return $image['file_path'] ?? null;
    }
}
