<?php

namespace App\Modules\Sales\Services;

use App\Modules\Sales\Contracts\SalesServiceInterface;
use App\Modules\Sales\Models\SalesImportItem;
use Illuminate\Support\Facades\DB;

class SalesService implements SalesServiceInterface
{
    public function getThisMonthRevenue(): float
    {
        return (float) SalesImportItem::whereMonth('transaction_at', now()->month)
            ->whereYear('transaction_at', now()->year)
            ->sum('amount');
    }

    public function getSalesTrend(int $days = 30): array
    {
        $startDate = now()->subDays($days - 1)->startOfDay();
        $salesData = SalesImportItem::where('transaction_at', '>=', $startDate)
            ->selectRaw('DATE(transaction_at) as date, SUM(amount) as total')
            ->groupBy('date')
            ->orderBy('date')
            ->get()
            ->mapWithKeys(function ($item) {
                return [$item->date => (int)$item->total];
            });

        $salesTrend = [];
        for ($i = 0; $i < $days; $i++) {
            $date = $startDate->copy()->addDays($i)->format('Y-m-d');
            $salesTrend[] = [
                'date' => $startDate->copy()->addDays($i)->format('m/d'),
                'amount' => $salesData[$date] ?? 0,
            ];
        }
        
        return $salesTrend;
    }

    public function getTopSellingProducts(int $limit = 5): \Illuminate\Support\Collection
    {
        return SalesImportItem::whereMonth('transaction_at', now()->month)
            ->whereYear('transaction_at', now()->year)
            ->select('product_code', 'product_id', DB::raw('SUM(amount) as total_amount'))
            ->groupBy('product_code', 'product_id')
            ->orderByDesc('total_amount')
            ->limit($limit)
            ->get();
    }

    public function getTopSellingByQuantity(int $limit = 5): \Illuminate\Support\Collection
    {
        return SalesImportItem::whereMonth('transaction_at', now()->month)
            ->whereYear('transaction_at', now()->year)
            ->select('product_code', 'product_id', DB::raw('SUM(quantity) as total_quantity'))
            ->groupBy('product_code', 'product_id')
            ->orderByDesc('total_quantity')
            ->limit($limit)
            ->get();
    }
}
