<?php

namespace App\Models;

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

class PerizinanStatus extends Model
{
    protected $table = 'perizinan_status';

    protected $fillable = [
        'kategori',
        'status_id',
        'label',
        'value',
        'api_last_updated',
        'sync_date'
    ];

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

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

        if (!$latestSyncDate) {
            // No data at all for this kategori
            return collect();
        }

        return self::where('kategori', $kategori)
            ->whereDate('sync_date', $latestSyncDate)
            ->get()
            ->keyBy('status_id');
    }

    /**
     * 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)
            ->get()
            ->keyBy('status_id');
    }
}
