<?php

declare(strict_types=1);

namespace App\Models\Barangay;

use App\Models\Model;
use App\Enums\Barangay\BlotterStatus;
use Hypervel\Database\Eloquent\SoftDeletes;

class Blotter extends Model
{
    use SoftDeletes;

    protected ?string $table = 'barangay_blotters';

    protected array $fillable = [
        'hashkey', 'blotter_no',
        'complainant_user_id', 'complainant_name', 'complainant_contact', 'complainant_address',
        'respondent_user_id', 'respondent_name', 'respondent_contact', 'respondent_address',
        'incident_type', 'incident_date', 'incident_location', 'narrative',
        'status', 'complaint_date', 'filed_by', 'assigned_officer_id',
        'resolution', 'settlement_type', 'endorsed_to', 'is_active',
        'created_by', 'updated_by',
    ];

    protected array $casts = [
        'incident_date'  => 'date',
        'complaint_date' => 'date',
        'is_active'      => 'boolean',
        'status'         => BlotterStatus::class,
    ];

    public function complainant()
    {
        return $this->belongsTo(\App\Models\User::class, 'complainant_user_id');
    }

    public function respondent()
    {
        return $this->belongsTo(\App\Models\User::class, 'respondent_user_id');
    }

    public function assignedOfficer()
    {
        return $this->belongsTo(\App\Models\User::class, 'assigned_officer_id');
    }

    public function hearings()
    {
        return $this->hasMany(BlotterHearing::class, 'blotter_id');
    }

    public function nextHearing()
    {
        return $this->hearings()->where('status', 'SCHEDULED')->orderBy('hearing_date')->first();
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public static function generateBlotterNo(): string
    {
        $year = date('Y');
        $count = static::whereYear('created_at', $year)->count() + 1;
        return sprintf('BLT-%s-%04d', $year, $count);
    }
}
