<?php

namespace App\Repositories\Eloquent;

use App\Models\Order;
use Illuminate\Database\Eloquent\Model;

class OrderRepository extends BaseRepository
{
    protected function resolveModel(): Model
    {
        return new Order();
    }

    public function getForBranch(int $branchId, int $limit = 50)
    {
        return $this->model->forBranch($branchId)
            ->with(['user', 'items.product.category'])
            ->orderBy('created_at', 'desc')
            ->limit($limit)
            ->get();
    }

    public function getActiveForBranch(int $branchId)
    {
        return $this->model->forBranch($branchId)
            ->active()
            ->with(['user', 'items.product.category'])
            ->orderBy('created_at', 'asc')
            ->get();
    }

    public function getActiveAll()
    {
        return $this->model->active()
            ->with(['user', 'branch', 'items.product.category'])
            ->orderBy('created_at', 'asc')
            ->get();
    }

    public function getByStatus(int $branchId, string $status)
    {
        return $this->model->forBranch($branchId)
            ->byStatus($status)
            ->with(['user', 'items.product.category'])
            ->orderBy('created_at', 'desc')
            ->get();
    }

    public function getTodayForBranch(int $branchId)
    {
        return $this->model->forBranch($branchId)
            ->today()
            ->with(['user', 'items.product.category', 'payments'])
            ->orderBy('created_at', 'desc')
            ->get();
    }

    public function findWithRelations(int $id): ?Order
    {
        return $this->model->with([
            'branch',
            'user',
            'items.product.category',
            'payments.user',
            'statusHistory.user'
        ])->find($id);
    }

    public function findByOrderNumber(string $orderNumber): ?Order
    {
        return $this->model->where('order_number', $orderNumber)->first();
    }

    public function getByDateRange(int $branchId, $startDate, $endDate)
    {
        return $this->model->forBranch($branchId)
            ->whereBetween('created_at', [$startDate, $endDate])
            ->with(['user', 'items', 'payments'])
            ->orderBy('created_at', 'desc')
            ->get();
    }
}
