<?php

namespace App\Models;

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

class TerakhirTerbit extends Model
{
    protected $table = 'TerakhirTerbit';
    protected $primaryKey = 'TerakhirTerbitID';

    protected $fillable = [
        'Kategori_ID',
        'NamaIzin',
        'Pemohon',
        'TanggalTerbit',
        'ApiLastUpdated',
        'SyncDate'
    ];

    protected $casts = [
        'TanggalTerbit' => 'date',
        'ApiLastUpdated' => 'datetime',
        'SyncDate' => '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_ID', $kategori)->max('SyncDate');

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

        return self::where('Kategori_ID', $kategori)
            ->whereDate('SyncDate', $latestSyncDate)
            ->orderBy('TanggalTerbit', '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_ID', $kategori)
            ->whereDate('SyncDate', $date)
            ->orderBy('TanggalTerbit', 'desc')
            ->limit(5)
            ->get();
    }
}
