<?php

namespace App\Models;

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

class PerizinanStatus extends Model
{
    protected $table = 'PerizinanStatus';
    protected $primaryKey = 'PerizinanStatusID';

    protected $fillable = [
        'Kategori_ID',
        'StatusID',
        'Label',
        'Value',
        'ApiLastUpdated',
        'SyncDate'
    ];

    protected $casts = [
        'ApiLastUpdated' => 'datetime',
        'SyncDate' => '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 SyncDate for the given kategori
        $latestSyncDate = self::where('Kategori_ID', $kategori)->max('SyncDate');

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

        return self::where('Kategori_ID', $kategori)
            ->whereDate('SyncDate', $latestSyncDate)
            ->get()
            ->keyBy('StatusID');
    }

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