<?php

namespace App\Http\Controllers\Tele;

use App\Http\Controllers\Controller;
use App\Models\TeleRecord;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();

        // KPIs
        $todayCount   = TeleRecord::forUser($user)->whereDate('created_at', now()->toDateString())->count();
        $withAudio    = TeleRecord::forUser($user)->whereNotNull('audio_path')->count();
        $totalRecords = TeleRecord::forUser($user)->count();

        // Recent
        $recent = TeleRecord::with('outlet')
            ->forUser($user)
            ->latest()
            ->limit(10)
            ->get();

        // NEW: Location-wise totals (brand + location)
        $byOutlet = TeleRecord::query()
            ->forUser($user)
            ->join('outlets', 'tele_records.outlet_id', '=', 'outlets.id')
            ->selectRaw('outlets.id, outlets.brand, outlets.location, COUNT(*) as total')
            ->groupBy('outlets.id', 'outlets.brand', 'outlets.location')
            ->orderByDesc('total')
            ->get();

        return view('telecalling.dashboard', compact(
            'todayCount', 'withAudio', 'totalRecords', 'recent', 'byOutlet'
        ));
    }
}
