<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'fixed_asset_id', 'disposal_date', 'proceeds', 'cost',
        'accum_depreciation', 'gain_loss', 'proceeds_account_id', 'gain_loss_account_id',
        'status', 'journal_entry_id', 'posted_at', 'notes',
        'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'number'         => 'required|max_length[40]',
        'fixed_asset_id' => 'required|is_natural_no_zero',
        'disposal_date'  => 'required|valid_date',
        'status'         => 'permit_empty|in_list[draft,posted,cancelled]',
    ];

    public function scopeForList(?string $search = null, ?string $status = null): self
    {
        $this->select('asset_disposals.*, fixed_assets.name as asset_name, fixed_assets.number as asset_number')
            ->join('fixed_assets', 'fixed_assets.id = asset_disposals.fixed_asset_id', 'left');

        if ($search) {
            $this->groupStart()
                ->like('asset_disposals.number', $search)
                ->orLike('fixed_assets.name', $search)
                ->orLike('fixed_assets.number', $search)
                ->orLike('asset_disposals.notes', $search)
                ->groupEnd();
        }

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

        return $this;
    }

    public function countForAsset(int $assetId): int
    {
        return $this->where('fixed_asset_id', $assetId)->countAllResults();
    }

    public function nextNumber(): string
    {
        $prefix = 'DSP-' . 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);
    }
}
