<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'company_id', 'invoice_id', 'sales_order_id', 'return_date', 'status',
        'subtotal', 'tax_amount', 'total', 'reason', 'notes',
        'approved_by', 'approved_at', 'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'number'      => 'required|max_length[40]',
        'company_id'  => 'required|is_natural_no_zero',
        'return_date' => 'required|valid_date',
        'status'      => 'permit_empty|in_list[draft,submitted,approved,completed,cancelled]',
    ];

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

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

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

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

        return $this;
    }

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