<?php

namespace App\Models;

use CodeIgniter\Model;

class DepreciationRunModel extends Model
{
    protected $table         = 'depreciation_runs';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';

    protected $allowedFields = [
        'number', 'period_start', 'period_end', 'run_date', 'total_amount',
        'status', 'journal_entry_id', 'posted_at', 'notes',
        'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'number'       => 'required|max_length[40]',
        'period_start' => 'required|valid_date',
        'period_end'   => 'required|valid_date',
        'run_date'     => 'required|valid_date',
        'status'       => 'permit_empty|in_list[draft,posted,cancelled]',
    ];

    public function scopeForList(?string $search = null, ?string $status = null): self
    {
        if ($search) {
            $this->groupStart()
                ->like('number', $search)
                ->orLike('notes', $search)
                ->groupEnd();
        }

        if ($status) {
            $this->where('status', $status);
        }

        return $this;
    }

    public function nextNumber(): string
    {
        $prefix = 'DPR-' . date('Ymd') . '-';
        $row = $this->like('number', $prefix, 'after')
            ->orderBy('id', 'DESC')
            ->first();

        $seq = 1;
        if ($row && preg_match('/-(\d+)$/', $row['number'], $m)) {
            $seq = (int) $m[1] + 1;
        }

        return $prefix . str_pad((string) $seq, 4, '0', STR_PAD_LEFT);
    }
}
