<?php

namespace App\Repositories;

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

class QuotationRepository extends BaseRepository
{
    protected function resolveModel(): Model
    {
        return new Quotation();
    }

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

    /**
     * Get quotations by RFQ
     */
    public function getByRfq(int $rfqId): Collection
    {
        return $this->where('rfq_no', $rfqId)->all();
    }

    /**
     * Get quotations by customer (non-vendor)
     */
    public function getByCustomer(int $customerId): Collection
    {
        return Quotation::nonVendor($customerId)->get();
    }

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

    /**
     * Get latest quotation number
     */
    public function getLatestQuotationNumber(): ?string
    {
        return Quotation::orderBy('id', 'desc')->value('quotation_no');
    }

    /**
     * Check if quotation number exists
     */
    public function quotationNumberExists(string $quotationNo): bool
    {
        return Quotation::where('quotation_no', $quotationNo)->exists();
    }

    /**
     * Get quotations for DataTable
     */
    public function getForDataTableWithRelations()
    {
        return Quotation::with(['customer', 'rfq'])->latest('quotation_date');
    }

    /**
     * Get quotations available for sales order
     */
    public function getAvailableForSalesOrder(): Collection
    {
        // Get quotations that don't have a sales order yet
        return Quotation::whereDoesntHave('salesOrder')
            ->with('customer')
            ->orderBy('quotation_date', 'desc')
            ->get();
    }

    /**
     * Search quotations
     */
    public function search(string $term): Collection
    {
        return Quotation::where('quotation_no', 'like', "%{$term}%")
            ->orWhere('description', 'like', "%{$term}%")
            ->orWhere('part_no', 'like', "%{$term}%")
            ->with('customer')
            ->get();
    }
}
