<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'code', 'name', 'bank_name', 'account_number', 'branch', 'currency',
        'account_id', 'opening_balance', 'status', 'notes', 'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'code'             => 'required|max_length[30]',
        'name'             => 'required|min_length[2]|max_length[150]',
        'currency'         => 'permit_empty|max_length[10]',
        'account_id'       => 'required|is_natural_no_zero',
        'opening_balance'  => 'permit_empty|decimal',
        'status'           => 'permit_empty|in_list[active,inactive]',
    ];

    public function scopeForList(?string $search = null, ?string $status = null): self
    {
        $this->select('bank_accounts.*, chart_of_accounts.code as account_code, chart_of_accounts.name as account_name')
            ->join('chart_of_accounts', 'chart_of_accounts.id = bank_accounts.account_id', 'left');

        if ($search) {
            $this->groupStart()
                ->like('bank_accounts.name', $search)
                ->orLike('bank_accounts.code', $search)
                ->orLike('bank_accounts.bank_name', $search)
                ->orLike('bank_accounts.account_number', $search)
                ->orLike('bank_accounts.notes', $search)
                ->groupEnd();
        }

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

        return $this;
    }

    public function getActive(): array
    {
        return $this->where('status', 'active')->orderBy('code', 'ASC')->findAll();
    }

    public function isCodeTaken(string $code, ?int $excludeId = null): bool
    {
        $builder = $this->where('code', strtoupper($code));
        if ($excludeId) {
            $builder->where('id !=', $excludeId);
        }

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