<?php

namespace App\Models;

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

class ReimbursementBatch extends BaseModel
{
    protected $table = 'reimbursement_batches';

    /**
     * Your table uses opened_at/closed_at (no created_at/updated_at).
     */
    public $timestamps = false;

    protected $fillable = [
        'title',
        'yearly_batch_number',
        'status',
        'school_year',
        'semester',
        'created_by',
        'closed_by',
        'opened_at',
        'closed_at',
        'notes',
    ];

    protected $casts = [
        'created_by'          => 'integer',
        'closed_by'           => 'integer',
        'yearly_batch_number' => 'integer',
        'opened_at'           => 'datetime',
        'closed_at'           => 'datetime',
    ];

    /* ============================================================
     * Status (enum-like)
     * ============================================================
     */

    public const STATUS_OPEN   = 'open';
    public const STATUS_CLOSED = 'closed';
    public const STATUS_DRAFT  = 'draft';

    public static function allowedStatuses(): array
    {
        return [
            self::STATUS_DRAFT,
            self::STATUS_OPEN,
            self::STATUS_CLOSED,
        ];
    }

    /* ============================================================
     * Relationships (optional but useful)
     * ============================================================
     */

    public function items(): HasMany
    {
        return $this->hasMany(ReimbursementBatchItem::class, 'batch_id');
    }

    public function adminFiles(): HasMany
    {
        return $this->hasMany(ReimbursementBatchAdminFile::class, 'batch_id');
    }

    public function creator(): BelongsTo
    {
        // Change Admin::class to your real admin/user model
        return $this->belongsTo(Admin::class, 'created_by');
    }

    public function closer(): BelongsTo
    {
        // Change Admin::class to your real admin/user model
        return $this->belongsTo(Admin::class, 'closed_by');
    }

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

    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 scopeStatus(Builder $q, string $status): Builder
    {
        return $q->where('status', $status);
    }

    public function scopeOpen(Builder $q): Builder
    {
        return $q->where('status', self::STATUS_OPEN);
    }

    public function scopeClosed(Builder $q): Builder
    {
        return $q->where('status', self::STATUS_CLOSED);
    }

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

    public function open(int $adminId, ?string $notes = null): self
    {
        $this->status = self::STATUS_OPEN;
        $this->opened_at = $this->opened_at ?: now();
        $this->created_by = $this->created_by ?: $adminId;

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

        $this->save();

        return $this;
    }

    public function close(int $adminId, ?string $notes = null): self
    {
        $this->status = self::STATUS_CLOSED;
        $this->closed_at = now();
        $this->closed_by = $adminId;

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

        $this->save();

        return $this;
    }

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

    public static function rules(?int $id = null): array
    {
        return [
            'title'               => ['required', 'string', 'max:255'],
            'status'              => ['required', 'string', 'in:' . implode(',', self::allowedStatuses())],
            'created_by'          => ['nullable', 'integer'],
            'closed_by'           => ['nullable', 'integer'],
            'opened_at'           => ['nullable', 'date'],
            'closed_at'           => ['nullable', 'date', 'after_or_equal:opened_at'],
            'notes'               => ['nullable', 'string', 'max:5000'],
            'school_year'         => ['nullable', 'string', 'max:20'],
            'semester'            => ['nullable', 'string', 'max:20'],
            'yearly_batch_number' => ['nullable', 'integer', 'min:1'],
        ];
    }
}