<?php
namespace App\Services;

use App\Models\Sale;
use App\Services\RateService;

class SalesDebtServices
{
    public function getUserDebt($userSelected = 0, $companyId = null, $admin = false)
    {
        if ($userSelected) {
            $query = Sale::with([
                'saleDetails' => function ($q) {
                    $q->with(['product', 'membershipUser.membership']);
                },
                'user.people',
            ])->where('status', 'pendiente');
            $query->where('user_id', $userSelected);
            $query->where('company_id', $companyId);

            $rateService = new RateService();
            $rate = $rateService->getActiveRate();
            $usdRate = $rate ? (float) $rate->usd_rate : 1;

            return $query->get()->map(function ($sale) use ($usdRate) {
                $sale->amount_rate = (float) ($sale->debt ?? 0) * $usdRate;
                return $sale;
            });
        }
    }
    public function getIdUserDebt($userId = null, $companyId = null)
    {
        $query = Sale::with(['user.people'])->where('status', 'pendiente');
        if ($userId !== null) {
            $query->where('user_id', $userId);
        }
        if ($companyId) {
            $query->where('company_id', $companyId);
        }

        $rateService = new RateService();
        $rate = $rateService->getActiveRate();
        $usdRate = $rate ? (float) $rate->usd_rate : 1;

        return $query->get()->map(function ($sale) use ($usdRate) {
            return [
                'sale_id' => $sale->id,
                'user_id' => $sale->user_id,
                'name' => $sale->user?->name,
                'last_name' => $sale->user?->people?->last_name,
                'amount_rate' => (float) ($sale->debt ?? 0) * $usdRate,
            ];
        })->unique('user_id')->sortBy(function ($item) {
            return strtolower($item['name'] ?? '');
        })->values()->toArray();
    }
    public function getTotalDebt($companyId = null)
    {
        $query = Sale::where('status', 'pendiente');
        if ($companyId) {
            $query->where('company_id', $companyId);
        }

        $totals = $query->selectRaw('COALESCE(SUM(debt), 0) as debt_total, COALESCE(SUM(aux_debt), 0) as aux_debt_total')
            ->first();

        return [
            'debt' => (float) ($totals?->debt_total ?? 0),
            'aux_debt' => (float) ($totals?->aux_debt_total ?? 0),
        ];
    }
    public function getSalesOnlyProducts($companyId = null)
    {
        $query = Sale::whereHas('saleDetails', function ($q) {
            $q->whereNotNull('product_id');
        });

        if ($companyId) {
            $query->where('company_id', $companyId);
        }

        $totals = $query->selectRaw('COALESCE(SUM(debt), 0) as debt_total, COALESCE(SUM(aux_debt), 0) as aux_debt_total')
            ->first();

        return [
            'debt' => (float) ($totals?->debt_total ?? 0),
            'aux_debt' => (float) ($totals?->aux_debt_total ?? 0),
        ];
    }
}