<?php

namespace App\Http\Controllers\FrontUser;

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

class ReportsController extends Controller
{
    public function index(Request $request)
    {
        $userId = Auth::id();

        // Aggregate stats
        $totalCalls = (int) Call::where('user_id', $userId)->count();
        $successfulCalls = (int) Call::where('user_id', $userId)->where('status', 'completed')->count();
        $totalDurationSeconds = (int) Call::where('user_id', $userId)->sum('duration');
        $totalCost = (float) Call::where('user_id', $userId)->sum('cost');

        // Last 30 days series
        $startDate = Carbon::now()->subDays(29)->startOfDay();
        $endDate = Carbon::now()->endOfDay();
        $byDay = Call::where('user_id', $userId)
            ->whereBetween('date_time', [$startDate, $endDate])
            ->selectRaw('DATE(date_time) as d, COUNT(*) c, SUM(cost) s')
            ->groupBy('d')
            ->orderBy('d')
            ->get()->keyBy('d');

        $labels30 = [];
        $calls30 = [];
        $spend30 = [];
        for ($i = 0; $i < 30; $i++) {
            $day = Carbon::now()->subDays(29 - $i)->format('Y-m-d');
            $labels30[] = Carbon::parse($day)->format('d M');
            $row = $byDay->get($day);
            $calls30[] = $row ? (int) $row->c : 0;
            $spend30[] = $row ? (float) $row->s : 0.0;
        }

        // Distribution by status
        $statusCounts = Call::where('user_id', $userId)
            ->selectRaw('status, COUNT(*) as c')
            ->groupBy('status')
            ->pluck('c', 'status');

        // Calls table with simple pagination (server-side)
        $calls = Call::where('user_id', $userId)
            ->orderByDesc('date_time')
            ->paginate(10);

        return view('FrontUser.Reports.index', compact(
            'totalCalls',
            'successfulCalls',
            'totalDurationSeconds',
            'totalCost',
            'labels30',
            'calls30',
            'spend30',
            'statusCounts',
            'calls'
        ));
    }

    public function export()
    {
        // Export reports logic
    }
}