<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'period_from', 'period_to', 'output_vat', 'input_vat', 'net_vat',
        'status', 'submitted_at', 'filed_at', 'notes', 'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'number'      => 'required|max_length[40]',
        'period_from' => 'required|valid_date',
        'period_to'   => 'required|valid_date',
        'status'      => 'permit_empty|in_list[draft,submitted,filed,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 = 'VAT-' . 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);
    }

    /**
     * True when another non-cancelled return overlaps the given period.
     */
    public function hasOverlappingPeriod(string $from, string $to, ?int $excludeId = null): bool
    {
        $builder = $this->where('status !=', 'cancelled')
            ->where('period_from <=', $to)
            ->where('period_to >=', $from);

        if ($excludeId) {
            $builder->where('id !=', $excludeId);
        }

        return $builder->countAllResults() > 0;
    }
}
