<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'service_visit_id', 'inspection_report_id', 'company_id',
        'signer_name', 'signer_title', 'signature_notes', 'signed_at',
        'status', 'captured_by', 'created_by', 'updated_by',
    ];

    public const STATUSES = ['captured', 'voided'];

    public function scopeForList(?string $search = null, ?string $status = null): self
    {
        $this->select(
            'fs_customer_signatures.*,
             companies.name AS company_name,
             fs_service_visits.number AS visit_number'
        )
            ->join('companies', 'companies.id = fs_customer_signatures.company_id', 'left')
            ->join('fs_service_visits', 'fs_service_visits.id = fs_customer_signatures.service_visit_id', 'left');

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

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

        return $this;
    }

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