<?php

namespace App\Repositories;

use App\Helpers\NumberHelper;
use App\Models\User;
use App\Repositories\Interfaces\CustomerRepositoryInterface;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

class CustomerRepository extends BaseRepository implements CustomerRepositoryInterface
{
    /**
     * {@inheritdoc}
     */
    protected function resolveModel(): Model
    {
        return new User();
    }

    /**
     * Override resetQuery to always filter customers.
     */
    protected function resetQuery(): self
    {
        $this->query = $this->model->newQuery()->where('is_customer', true);
        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getActive(): Collection
    {
        return $this->where('is_active', true)->all();
    }

    /**
     * {@inheritdoc}
     */
    public function getInactive(): Collection
    {
        return $this->where('is_active', false)->all();
    }

    /**
     * {@inheritdoc}
     */
    public function search(string $term): self
    {
        $normalizedTerm = NumberHelper::persianToEnglish($term);
        
        $this->query = $this->query->where(function ($q) use ($term, $normalizedTerm) {
            $q->where('name', 'like', "%{$term}%")
              ->orWhere('mobile', 'like', "%{$normalizedTerm}%");
        });

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function createdBetween(string $from, string $to): self
    {
        $this->query = $this->query
            ->whereDate('created_at', '>=', $from)
            ->whereDate('created_at', '<=', $to);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function withOrders(): self
    {
        return $this->with(['orders']);
    }

    /**
     * {@inheritdoc}
     */
    public function findByMobile(string $mobile): ?User
    {
        return $this->findFirstBy('mobile', $mobile);
    }

    /**
     * {@inheritdoc}
     */
    public function forceDeleteByMobile(string $mobile): int
    {
        return User::onlyTrashed()
            ->where('is_customer', true)
            ->where('mobile', $mobile)
            ->forceDelete();
    }

    /**
     * Get customers filtered by status.
     */
    public function filterByStatus(?string $status): self
    {
        if ($status === 'active') {
            $this->query = $this->query->where('is_active', true);
        } elseif ($status === 'inactive') {
            $this->query = $this->query->where('is_active', false);
        }

        return $this;
    }
}
