<?php

namespace App\Database\Eloquent;

use App\Models\Scopes\BranchScope;
use App\Support\PhoneNumber;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\Builder as QueryBuilder;

class CustomerBuilder extends Builder
{
    public function __construct(QueryBuilder $query)
    {
        parent::__construct($query);
        $this->withGlobalScope(BranchScope::class, new BranchScope());
    }

    public function where($column, $operator = null, $value = null, $boolean = 'and')
    {
        $arguments = func_num_args();

        if (is_string($column)) {
            $field = str_contains($column, '.')
                ? substr($column, strrpos($column, '.') + 1)
                : $column;

            if (in_array($field, ['phone', 'alternative_phone'], true)) {
                if ($arguments === 2 && is_scalar($operator)) {
                    $operator = PhoneNumber::normalize($operator) ?? $operator;
                } elseif ($arguments >= 3 && $operator === '=' && is_scalar($value)) {
                    $value = PhoneNumber::normalize($value) ?? $value;
                }
            }
        }

        return match ($arguments) {
            1 => parent::where($column),
            2 => parent::where($column, $operator),
            3 => parent::where($column, $operator, $value),
            default => parent::where($column, $operator, $value, $boolean),
        };
    }
}
