<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class TerakhirTerbit extends Model
{
    protected $table = 'terakhir_terbit';

    protected $fillable = [
        'kategori',
        'nama_izin',
        'pemohon',
        'tanggal_terbit',
        'api_last_updated',
        'sync_date'
    ];

    protected $casts = [
        'tanggal_terbit' => 'date',
        'api_last_updated' => 'datetime',
        'sync_date' => 'date'
    ];

    /**
     * Get latest data by kategori for the latest available sync_date, ordered by tanggal_terbit DESC.
     * Falls back to the most recent data if today's data is absent.
     */
    public static function getLatestByKategori($kategori)
    {
        $latestSyncDate = self::where('kategori', $kategori)->max('sync_date');

        if (!$latestSyncDate) {
            return collect();
        }

        return self::where('kategori', $kategori)
            ->whereDate('sync_date', $latestSyncDate)
            ->orderBy('tanggal_terbit', 'desc')
            ->limit(5)
            ->get();
    }

    /**
     * Get data by kategori and specific date, ordered by tanggal_terbit DESC
     */
    public static function getByKategoriAndDate($kategori, $date)
    {
        return self::where('kategori', $kategori)
            ->whereDate('sync_date', $date)
            ->orderBy('tanggal_terbit', 'desc')
            ->limit(5)
            ->get();
    }
}
