<?php

namespace App\Http\Controllers\FrontUser;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Call;
use App\Models\WalletTransaction;
use Illuminate\Support\Carbon;

class DashboardController extends Controller
{
    public function index()
    {
        $user = Auth::user();

        $walletBalance = $user->wallet_balance ?? 0.0;
        $lastRecharge = WalletTransaction::where('user_id', $user->id)
            ->where('type', 'credit')
            ->where('status', 'success')
            ->latest('id')
            ->first();

        $totalCalls = Call::where('user_id', $user->id)->count();
        $totalDurationSeconds = (int) Call::where('user_id', $user->id)->sum('duration');
        $totalMoney = (float) Call::where('user_id', $user->id)->sum('cost');

        $recentCalls = Call::where('user_id', $user->id)
            ->orderByDesc('date_time')
            ->take(5)
            ->get();

        $scheduledCalls = Call::where('user_id', $user->id)
            ->where('status', 'pending')
            ->orderBy('date_time')
            ->take(5)
            ->get();

        // Build 7-day charts data
        $startDate = Carbon::now()->subDays(6)->startOfDay();
        $endDate = Carbon::now()->endOfDay();

        $callsByDay = Call::where('user_id', $user->id)
            ->whereBetween('date_time', [$startDate, $endDate])
            ->selectRaw('DATE(date_time) as d, COUNT(*) as c, SUM(cost) as s, SUM(duration) as dur')
            ->groupBy('d')
            ->orderBy('d')
            ->get()
            ->keyBy('d');

        $chartLabels = [];
        $chartCalls = [];
        $chartSpend = [];
        $chartDurationMinutes = [];

        for ($i = 0; $i < 7; $i++) {
            $day = Carbon::now()->subDays(6 - $i)->format('Y-m-d');
            $chartLabels[] = Carbon::parse($day)->format('d M');
            $dayRow = $callsByDay->get($day);
            $chartCalls[] = $dayRow ? (int) $dayRow->c : 0;
            $chartSpend[] = $dayRow ? (float) $dayRow->s : 0.0;
            $chartDurationMinutes[] = $dayRow ? (int) floor(((int) $dayRow->dur) / 60) : 0;
        }

        return view('FrontUser.home', compact(
            'user',
            'walletBalance',
            'lastRecharge',
            'totalCalls',
            'totalDurationSeconds',
            'totalMoney',
            'recentCalls',
            'scheduledCalls',
            'chartLabels',
            'chartCalls',
            'chartSpend',
            'chartDurationMinutes'
        ));
    }
}