<?php

namespace App\Models;

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

class RekomposisiUpa extends Model
{
    use HasFactory;

    protected $table = 'tbl_rekomposisi_upa';

    protected $fillable = [
        'nomor_sk',
        'tanggal_sk',
        'tanggal_rapat',
        'dpc_id',
        'judul_sk',
        'menimbang_a',
        'menimbang_b',
        'menimbang_c',
        'mengingat_1',
        'mengingat_2',
        'mengingat_3',
        'memperhatikan',
        'memutuskan',
        'menetapkan',
        'pertama',
        'kedua',
        'ketiga',
        'keempat',
        'ditetapkan_di',
        'nomor_sk_lampiran',
        'ditetapkan_tanggal',
        'ketua_nama',
        'ketua_jabatan',
        'status',
        'created_by',
        'approved_by',
        'catatan'
    ];

    protected $casts = [
        'tanggal_sk' => 'date',
        'tanggal_rapat' => 'date',
        'ditetapkan_tanggal' => 'date',
    ];

    // ===== RELATIONSHIPS =====
    public function dpc()
    {
        return $this->belongsTo(Dpc::class, 'dpc_id', 'dpc_id');
    }

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function approver()
    {
        return $this->belongsTo(User::class, 'approved_by');
    }

    public function details()
    {
        return $this->hasMany(RekomposisiUpaDetail::class, 'rekomposisi_id');
    }

    // ===== ACCESSORS =====
    public function getTanggalSkFormattedAttribute()
    {
        return $this->tanggal_sk ? Carbon::parse($this->tanggal_sk)->format('d F Y') : null;
    }

    public function getDitetapkanTanggalFormattedAttribute()
    {
        return $this->ditetapkan_tanggal ? Carbon::parse($this->ditetapkan_tanggal)->format('d F Y') : null;
    }

    public function getStatusBadgeClassAttribute()
    {
        return match($this->status) {
            'Draft' => 'warning',
            'Approved' => 'success',
            'Published' => 'info',
            default => 'secondary'
        };
    }

    public function getStatusTextAttribute()
    {
        return match($this->status) {
            'Draft' => 'Draft',
            'Approved' => 'Disetujui',
            'Published' => 'Dipublikasikan',
            default => 'Tidak Diketahui'
        };
    }

    // ===== SCOPES =====
    public function scopeDraft($query)
    {
        return $query->where('status', 'Draft');
    }

    public function scopeApproved($query)
    {
        return $query->where('status', 'Approved');
    }

    public function scopePublished($query)
    {
        return $query->where('status', 'Published');
    }

    public function scopeByDpc($query, $dpcId)
    {
        return $query->where('dpc_id', $dpcId);
    }

    // ===== STATIC METHODS =====
    public static function generateNomorSK($dpcId = null)
    {
        $year = date('Y');
        $month = date('m');
        $monthName = [
            '01' => 'I', '02' => 'II', '03' => 'III', '04' => 'IV',
            '05' => 'V', '06' => 'VI', '07' => 'VII', '08' => 'VIII',
            '09' => 'IX', '10' => 'X', '11' => 'XI', '12' => 'XII'
        ];

        $monthRoman = $monthName[$month] ?? $month;
        
        // Get count for this month
        $count = static::whereYear('created_at', $year)
                     ->whereMonth('created_at', $month)
                     ->count() + 1;

        $paddedCount = str_pad($count, 3, '0', STR_PAD_LEFT);
        
        return "{$paddedCount}/D/SK/BK/AI-04-PKS/{$monthRoman}/{$year}";
    }

    // ===== HELPER METHODS =====
    public function canEdit()
    {
        return $this->status === 'Draft';
    }

    public function canApprove()
    {
        return $this->status === 'Draft';
    }

    public function canPublish()
    {
        return $this->status === 'Approved';
    }

    public function approve($userId)
    {
        $this->update([
            'status' => 'Approved',
            'approved_by' => $userId,
            'approved_at' => now()
        ]);
    }

    public function publish()
    {
        $this->update([
            'status' => 'Published',
            'published_at' => now()
        ]);
    }

    public function getTotalAnggotaAttribute()
    {
        return $this->details()->count();
    }

    public function getTotalUpaAttribute()
    {
        return $this->details()->distinct('kode_upa')->count();
    }

    // ===== BOOT METHOD =====
    protected static function boot()
    {
        parent::boot();
        
        // Auto-generate nomor SK if not provided
        static::creating(function ($rekomposisi) {
            if (empty($rekomposisi->nomor_sk)) {
                $rekomposisi->nomor_sk = static::generateNomorSK($rekomposisi->dpc_id);
            }
        });
    }
}
