<?php

namespace App\Models;

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

class FastestPermohonan extends Model
{
    protected $table = 'fastest_permohonan';

    protected $fillable = [
        'kategori',
        'nama',
        'total',
        'durasi_pemohon',
        'durasi_petugas',
        'api_last_updated',
        'sync_date'
    ];

    protected $casts = [
        'api_last_updated' => 'datetime',
        'sync_date' => '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', $kategori)->max('sync_date');

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

        return self::where('kategori', $kategori)
            ->whereDate('sync_date', $latestSyncDate)
            ->orderBy('id') // Keep API order by using insertion order
            ->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', $kategori)
            ->whereDate('sync_date', $date)
            ->orderBy('id') // Keep API order by using insertion order
            ->limit(5)
            ->get();
    }
}
