<?php

namespace App\Repositories;

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

class RfqRepository extends BaseRepository
{
    protected function resolveModel(): Model
    {
        return new Rfq();
    }

    /**
     * Get all RFQs with customer info
     */
    public function getAllWithCustomer(): Collection
    {
        return $this->with(['customerInfo'])->orderBy('rfq_date', 'desc')->all();
    }

    /**
     * Get RFQs by customer
     */
    public function getByCustomer(int $customerId): Collection
    {
        return $this->where('customer', $customerId)->orderBy('rfq_date', 'desc')->all();
    }

    /**
     * Get RFQs by type
     */
    public function getByType(string $type): Collection
    {
        return $this->where('rfq_type', $type)->all();
    }

    /**
     * Get RFQs by date range
     */
    public function getByDateRange(string $startDate, string $endDate): Collection
    {
        return $this->whereBetween('rfq_date', [$startDate, $endDate])->all();
    }

    /**
     * Get latest RFQ number
     */
    public function getLatestRfqNumber(): ?string
    {
        return Rfq::orderBy('id', 'desc')->value('rfq_no');
    }

    /**
     * Check if RFQ number exists
     */
    public function rfqNumberExists(string $rfqNo): bool
    {
        return Rfq::where('rfq_no', $rfqNo)->exists();
    }

    /**
     * Get RFQs for DataTable with customer info
     */
    public function getForDataTableWithRelations()
    {
        return Rfq::with('customerInfo')->latest('rfq_date');
    }

    /**
     * Search RFQs
     */
    public function search(string $term): Collection
    {
        return Rfq::where('rfq_no', 'like', "%{$term}%")
            ->orWhere('description', 'like', "%{$term}%")
            ->orWhere('part_no', 'like', "%{$term}%")
            ->with('customerInfo')
            ->get();
    }
}
