<?php

namespace App\Repositories;

use App\Models\CustomerVendor;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;

class CustomerVendorRepository extends BaseRepository
{
    protected function resolveModel(): Model
    {
        return new CustomerVendor();
    }

    /**
     * Get all customers
     */
    public function getCustomers(): Collection
    {
        return $this->whereIn('company_role', ['Customer', 'Both'])
            ->orderBy('company', 'asc')
            ->all();
    }

    /**
     * Get all vendors
     */
    public function getVendors(): Collection
    {
        return $this->whereIn('company_role', ['Vendor', 'Both'])
            ->orderBy('company', 'asc')
            ->all();
    }

    /**
     * Get active customers/vendors
     */
    public function getActive(): Collection
    {
        return $this->where('status', 'active')
            ->orderBy('company', 'asc')
            ->all();
    }

    /**
     * Get by company role
     */
    public function getByRole(string $role): Collection
    {
        return $this->where('company_role', $role)
            ->orderBy('company', 'asc')
            ->all();
    }

    /**
     * Search customers/vendors
     */
    public function search(string $term): Collection
    {
        $query = $this->getQuery();
        $query->where(function ($q) use ($term) {
            $q->where('company', 'like', "%{$term}%")
                ->orWhere('email', 'like', "%{$term}%")
                ->orWhere('mobile', 'like', "%{$term}%")
                ->orWhere('gstno', 'like', "%{$term}%");
        });
        $result = $query->get();
        $this->resetQuery();
        return $result;
    }

    /**
     * Get with contact persons
     */
    public function getWithContacts(): Collection
    {
        return $this->with(['contactPersons'])
            ->orderBy('company', 'asc')
            ->all();
    }
}
