<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'company_id', 'invoice_id', 'sales_return_id', 'refund_date',
        'amount', 'method', 'status', 'notes', 'processed_at',
        'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'number'      => 'required|max_length[40]',
        'company_id'  => 'required|is_natural_no_zero',
        'refund_date' => 'required|valid_date',
        'amount'      => 'required|decimal',
        'status'      => 'permit_empty|in_list[draft,pending,processed,cancelled]',
    ];

    public function scopeForList(?string $search = null, ?string $status = null, ?int $companyId = null): self
    {
        $this->select('refunds.*, companies.name as company_name, invoices.number as invoice_number, sales_returns.number as return_number')
            ->join('companies', 'companies.id = refunds.company_id', 'left')
            ->join('invoices', 'invoices.id = refunds.invoice_id', 'left')
            ->join('sales_returns', 'sales_returns.id = refunds.sales_return_id', 'left');

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

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

        if ($companyId) {
            $this->where('refunds.company_id', $companyId);
        }

        return $this;
    }

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