<?php

namespace App\Models;

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

class FastestPermohonan extends Model
{
    protected $table = 'FastestPermohonan';
    protected $primaryKey = 'FastestPermohonanID';

    protected $fillable = [
        'Kategori_ID',
        'Nama',
        'Total',
        'DurasiPemohon',
        'DurasiPetugas',
        'ApiLastUpdated',
        'SyncDate'
    ];

    protected $casts = [
        'ApiLastUpdated' => 'datetime',
        'SyncDate' => 'date',
        'Total' => 'integer'
    ];

    /**
     * Get fastest permohonan by kategori for the latest available sync_date.
     * Falls back to the most recent data if today's data is absent.
     * Since API already provides fastest data in correct order, preserve insertion order via id.
     */
    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('FastestPermohonanID')
            ->limit(5)
            ->get();
    }

    /**
     * Get data for specific kategori and date
     */
    public static function getByKategoriAndDate($kategori, $date = null)
    {
        $date = $date ?: Carbon::today();

        return self::where('Kategori_ID', $kategori)
            ->whereDate('SyncDate', $date)
            ->orderBy('FastestPermohonanID') // Keep API order by using insertion order
            ->limit(5)
            ->get();
    }
}
