<?php

namespace App\Traits;

use App\Models\BettingDetail;

trait AmountAnalytics
{
    public function totalBettingAmount($period = null): float
    {
        $query = $this->transactions()->where('purpose', 'game_betting');
        if ($period) {
            $query->whereBetween('created_at', $this->getDateRange($period));
        }
        return $query->sum('amount');
    }

    public function totalWinningAmount($period = null): float
    {
        $query = $this->transactions()->where('purpose', 'game_winning');
        if ($period) {
            $query->whereBetween('created_at', $this->getDateRange($period));
        }
        return $query->sum('amount');
    }

    public function totalLossAmount($period = null): float
    {
        $query = BettingDetail::loss();
        if ($period) {
            $query->whereBetween('created_at', $this->getDateRange($period));
        }
        return $query->sum('amount');
    }

    public function totalCommissionAmount($period = null): float
    {
        $query = $this->transactions()->where('purpose', 'commission');
        if ($period) {
            $query->whereBetween('created_at', $this->getDateRange($period));
        }
        return $query->sum('amount');
    }

    protected function getDateRange($period)
    {
        switch ($period) {
            case 'today':
                return [now()->startOfDay(), now()->endOfDay()];
            case 'last3days':
                return [now()->subDays(2)->startOfDay(), now()->endOfDay()];
            case 'last7days':
                return [now()->subDays(6)->startOfDay(), now()->endOfDay()];
            case 'last30days':
                return [now()->subDays(29)->startOfDay(), now()->endOfDay()];
            default:
                return null;
        }
    }
}
