<?php

namespace App\Repositories\Eloquent;

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

class ExpenseRepository extends BaseRepository
{
    protected function resolveModel(): Model
    {
        return new Expense();
    }

    public function getForBranch(int $branchId)
    {
        return $this->model->where('branch_id', $branchId)
            ->with(['category', 'user', 'approver'])
            ->orderBy('expense_date', 'desc')
            ->get();
    }

    public function getByStatus(int $branchId, string $status)
    {
        return $this->model->where('branch_id', $branchId)
            ->where('status', $status)
            ->with(['category', 'user', 'approver'])
            ->orderBy('expense_date', 'desc')
            ->get();
    }

    public function getPending(int $branchId)
    {
        return $this->model->where('branch_id', $branchId)
            ->where('status', 'pending')
            ->with(['category', 'user'])
            ->orderBy('created_at', 'asc')
            ->get();
    }

    public function getByDateRange(int $branchId, $startDate, $endDate)
    {
        return $this->model->where('branch_id', $branchId)
            ->whereBetween('expense_date', [$startDate, $endDate])
            ->where('status', 'approved')
            ->with(['category', 'user'])
            ->orderBy('expense_date', 'desc')
            ->get();
    }

    public function getSummaryByCategory(int $branchId, $startDate, $endDate)
    {
        return $this->model->where('branch_id', $branchId)
            ->whereBetween('expense_date', [$startDate, $endDate])
            ->where('status', 'approved')
            ->selectRaw('expense_category_id, COUNT(*) as count, SUM(amount) as total')
            ->groupBy('expense_category_id')
            ->with('category')
            ->get();
    }

    public function findWithRelations(int $id): ?Expense
    {
        return $this->model->with(['branch', 'category', 'user', 'approver'])->find($id);
    }
}
