<?php

namespace App\Services;

use App\Models\User;
use App\Models\Sell;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Carbon\Carbon;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\DB;

class ChartService
{
    public function getManualSalesData(Request $request)
    {
        $period = $request->input('period', '7days');
        
        $endDate = Carbon::today();
        $startDate = $endDate->copy();
        
        switch ($period) {
            case '30days':
                $startDate->subDays(29);
                break;
            case '6months':
                $startDate->subMonths(6)->startOfMonth();
                break;
            default: // 7days
                $startDate->subDays(6);
        }
    
        $salesData = Sell::select(
            DB::raw('DATE(updated_at) as date'),
            DB::raw('SUM(amount * quantity) as total'),
            DB::raw('SUM((amount - initial_price) * quantity) as profits')
        )
        ->where('user_id', auth()->user()->id)
        ->where('type', 'manual_sell')
        ->where('status', 1)
        ->whereBetween('updated_at', [$startDate, $endDate])
        ->groupBy('date')
        ->orderBy('date')
        ->get();
    
        return response()->json($salesData);
    }
}