<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ReimbursementBatchItem extends BaseModel
{
    protected $table = 'reimbursement_batch_items';

    /**
     * Table uses assigned_at/unassigned_at (no created_at/updated_at).
     */
    public $timestamps = false;

    protected $fillable = [
        'batch_id',
        'expense_id',
        'reimbursement_id',
        'admin_id',
        'assigned_at',
        'unassigned_at',
        'notes',
        'school_year',
        'semester',
    ];

    protected $casts = [
        'batch_id'         => 'integer',
        'expense_id'       => 'integer',
        'reimbursement_id' => 'integer',
        'admin_id'         => 'integer',
        'assigned_at'      => 'datetime',
        'unassigned_at'    => 'datetime',
    ];

    /* ============================================================
     * Relationships (optional)
     * ============================================================
     */

    public function batch(): BelongsTo
    {
        return $this->belongsTo(ReimbursementBatch::class, 'batch_id');
    }

    public function expense(): BelongsTo
    {
        return $this->belongsTo(Expense::class, 'expense_id');
    }

    public function reimbursement(): BelongsTo
    {
        return $this->belongsTo(Reimbursement::class, 'reimbursement_id');
    }

    public function admin(): BelongsTo
    {
        // Change to User/Admin model used in your app
        return $this->belongsTo(Admin::class, 'admin_id');
    }

    /* ============================================================
     * Scopes
     * ============================================================
     */

    public function scopeForBatch(Builder $q, int $batchId): Builder
    {
        return $q->where('batch_id', $batchId);
    }

    public function scopeForSchoolYear(Builder $q, string $schoolYear): Builder
    {
        return $q->where('school_year', $schoolYear);
    }

    public function scopeForSemester(Builder $q, string $semester): Builder
    {
        return $q->where('semester', $semester);
    }

    public function scopeAssigned(Builder $q): Builder
    {
        return $q->whereNotNull('admin_id')
                 ->whereNotNull('assigned_at')
                 ->whereNull('unassigned_at');
    }

    public function scopeUnassigned(Builder $q): Builder
    {
        return $q->whereNull('admin_id')
                 ->whereNull('assigned_at');
    }

    /* ============================================================
     * Helpers
     * ============================================================
     */

    public function assignToAdmin(int $adminId, ?string $notes = null): self
    {
        $this->admin_id = $adminId;
        $this->assigned_at = $this->assigned_at ?: now();
        $this->unassigned_at = null;

        if ($notes !== null) {
            $this->notes = $notes;
        }

        $this->save();

        return $this;
    }

    public function unassign(?string $notes = null): self
    {
        $this->admin_id = null;
        $this->unassigned_at = now();

        if ($notes !== null) {
            $this->notes = $notes;
        }

        $this->save();

        return $this;
    }

    /* ============================================================
     * Optional validation helper (FormRequest/controller)
     * ============================================================
     */

    public static function rules(bool $updating = false): array
    {
        return [
            'batch_id'         => [$updating ? 'sometimes' : 'required', 'integer', 'min:1', 'exists:reimbursement_batches,id'],
            'expense_id'       => ['nullable', 'integer', 'exists:expenses,id'],
            'reimbursement_id' => ['nullable', 'integer', 'exists:reimbursements,id'],
            'admin_id'         => ['nullable', 'integer'], // add exists rule if you know the table
            'assigned_at'      => ['nullable', 'date'],
            'unassigned_at'    => ['nullable', 'date', 'after_or_equal:assigned_at'],
            'notes'            => ['nullable', 'string', 'max:5000'],
            'school_year'      => ['nullable', 'string', 'max:20'],
            'semester'         => ['nullable', 'string', 'max:20'],
        ];
    }
}