<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'request_type', 'title', 'description', 'amount',
        'requester_user_id', 'approver_user_id', 'status', 'rejection_reason',
        'decided_at', 'created_by', 'updated_by',
    ];

    public const TYPES = ['expense', 'work', 'purchase', 'leave', 'general'];

    public const STATUSES = ['pending', 'approved', 'rejected', 'cancelled'];

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

    public function scopeForList(?string $search = null, ?string $status = null, ?string $type = null): self
    {
        $this->select(
            'operations_approval_requests.*,
             CONCAT(req.first_name, \' \', req.last_name) AS requester_name,
             CONCAT(apr.first_name, \' \', apr.last_name) AS approver_name'
        )
            ->join('users req', 'req.id = operations_approval_requests.requester_user_id', 'left')
            ->join('users apr', 'apr.id = operations_approval_requests.approver_user_id', 'left');

        if ($search) {
            $this->groupStart()
                ->like('operations_approval_requests.number', $search)
                ->orLike('operations_approval_requests.title', $search)
                ->orLike('operations_approval_requests.description', $search)
                ->groupEnd();
        }

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

        if ($type) {
            $this->where('operations_approval_requests.request_type', $type);
        }

        return $this;
    }

    /**
     * @return list<array>
     */
    public function forRequester(int $userId, ?string $search = null, ?string $status = null): array
    {
        return $this->scopeForList($search, $status)
            ->where('operations_approval_requests.requester_user_id', $userId)
            ->orderBy('operations_approval_requests.id', 'DESC')
            ->findAll();
    }

    /**
     * @return list<array>
     */
    public function pendingForApprover(int $userId, ?string $search = null): array
    {
        return $this->scopeForList($search, 'pending')
            ->where('operations_approval_requests.approver_user_id', $userId)
            ->orderBy('operations_approval_requests.id', 'ASC')
            ->findAll();
    }
}
