<?php

namespace App\Core\Repositories;

use App\Models\Estimate;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Pagination\LengthAwarePaginator;

/**
 * Estimate Repository
 * Handles all database operations for estimates
 */
class EstimateRepository
{
    /**
     * Get all estimates
     */
    public function getAll(): Collection
    {
        return Estimate::with(['customer', 'items'])->get();
    }

    /**
     * Get paginated estimates
     */
    public function getPaginated(int $perPage = 15, array $filters = []): LengthAwarePaginator
    {
        $query = Estimate::with(['customer', 'items']);

        // Apply filters
        if (isset($filters['status'])) {
            $query->where('status', $filters['status']);
        }

        if (isset($filters['customer_id'])) {
            $query->where('customer_id', $filters['customer_id']);
        }

        if (isset($filters['date_from'])) {
            $query->where('issue_date', '>=', $filters['date_from']);
        }

        if (isset($filters['date_to'])) {
            $query->where('issue_date', '<=', $filters['date_to']);
        }

        return $query->orderBy('created_at', 'desc')->paginate($perPage);
    }

    /**
     * Get estimate by ID
     */
    public function getById(int $id): ?Estimate
    {
        return Estimate::with(['customer', 'items'])->find($id);
    }

    /**
     * Get estimate by estimate number
     */
    public function getByEstimateNumber(string $estimateNumber): ?Estimate
    {
        return Estimate::where('estimate_number', $estimateNumber)->first();
    }

    /**
     * Create a new estimate
     */
    public function create(array $data): Estimate
    {
        return Estimate::create($data);
    }

    /**
     * Update an estimate
     */
    public function update(Estimate $estimate, array $data): bool
    {
        return $estimate->update($data);
    }

    /**
     * Delete an estimate
     */
    public function delete(Estimate $estimate): bool
    {
        return $estimate->delete();
    }
}
