<?php

namespace Modules\WhatsApp\Http\Controllers;

use Illuminate\Routing\Controller;
use Modules\WhatsApp\Entities\WaChannel;
use Modules\WhatsApp\Entities\WaMessage;

class WaDashboardController extends Controller
{
    public function index()
    {
        if (!auth()->user()->can('whatsapp.access_module')) {
            abort(403, 'Unauthorized action.');
        }
        $businessId = request()->session()->get('user.business_id');

        $channels = WaChannel::where('business_id', $businessId)->get();

        $stats = [
            'channels'      => $channels->count(),
            'connected'     => $channels->where('status', 'active')->count(),
            'disconnected'  => $channels->whereIn('status', ['disconnected'])->count(),
            'pending'       => WaMessage::where('business_id', $businessId)->whereIn('status', ['pending', 'queued'])->count(),
            'sent_today'    => WaMessage::where('business_id', $businessId)
                                ->where('direction', 'out')->whereIn('status', ['sent', 'delivered', 'read'])
                                ->whereDate('sent_at', today())->count(),
            'failed'        => WaMessage::where('business_id', $businessId)->where('status', 'failed')->count(),
        ];

        // Channels that need attention (disconnected with messages waiting).
        $needAttention = $channels->where('status', 'disconnected');

        return view('whatsapp::dashboard.index', compact('stats', 'channels', 'needAttention'));
    }
}
