<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\View\View;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

// Explicitly import models for better readability and IDE support
use App\Models\Client;
use App\Models\UserActivity;
use App\Models\StaffMember;
use App\Models\NationalHoliday;
use App\Models\DailyQuote;
use App\Models\NetworkOps;

class DashboardController extends Controller
{
    public function index(): View
    {
        // Grouped OR clauses inside a closure to prevent query bleeding
        $ussd_clients = Client::where(function ($query) {
            $query->where('services', 'LIKE', '%ussd%')
                  ->orWhere('services', 'LIKE', '%A2P%');
        })->count();

        $airtime_clients = Client::where('services', 'LIKE', '%airtime%')->count();
        $sms_clients = Client::where('services', 'LIKE', '%sms%')->count();
        $voice_clients = Client::where('services', 'LIKE', '%ivr%')->count();

        // Cleaned up the null/empty checks and removed the dangerous global orWhere
        $expiring_contracts = Client::where('contract_auto_renew', '!=', 'YES')
            ->whereNotNull('contract_validity')
            ->where('contract_validity', '!=', '')
            ->orderBy('contract_validity', 'ASC')
            ->take(5)
            ->get();

        $user_activities = UserActivity::where('user_id', '>', 1)
            ->with('userInfo')
            ->orderBy('created_at', 'DESC')
            ->take(5)
            ->get();

        $recent_clients = Client::with('auth_user_info')
            ->orderBy('id', 'DESC')
            ->take(5)
            ->get();

        // Cleaner raw query for upcoming birthdays ignoring the current year
        $upcoming_birthdays = StaffMember::whereRaw("DATE_FORMAT(dob, '%m-%d') >= DATE_FORMAT(CURDATE(), '%m-%d')")
            ->orderByRaw("DATE_FORMAT(dob, '%m-%d') ASC")
            ->take(5)
            ->get();

        $upcoming_hodidays = NationalHoliday::whereDate('event_date', '>=', Carbon::today())
            ->orderBy('event_date', 'ASC')
            ->take(15)
            ->get();

        $main_quote = DailyQuote::where('status', 'active')->first();

        return view('dashboard.index_two', [
            'page_title'         => 'Dashboard',
            'sms'                => $sms_clients,
            'ussd'               => $ussd_clients,
            'voice'              => $voice_clients,
            'airtime'            => $airtime_clients,
            'total'              => Client::count(),
            'main_quote'         => $main_quote,
            'recent_clients'     => $recent_clients,
            'user_activities'    => $user_activities,
            'expiring_contracts' => $expiring_contracts,
            'upcoming_birthdays' => $upcoming_birthdays,
            'upcoming_hodidays'  => $upcoming_hodidays
        ]);
    }

    public function getEvents(): JsonResponse
    {
        $event_arr = [
            [
                "title" => 'Airtel MW Top Up',
                "start" => date("Y-m-d") // Fixed format: Most JS calendars expect Y-m-d, not Y, m, d
            ],
            [
                "title" => 'Airtel MW Top Down',
                "start" => date("Y-m-d")
            ],
        ];

        return response()->json($event_arr);
    }

    public function getQuotes(): JsonResponse
    {
        // Replaced complex raw SQL with Laravel's native randomized sorting
        $daily_quote = DailyQuote::inRandomOrder()->first();
        
        return response()->json($daily_quote);
    }

    public function getMnosContracts(): JsonResponse
    {
        $threeMonthsLater = Carbon::now()->addMonths(3)->format('m-d');
        $currentMonth = Carbon::now()->format('m');

        // Added ->count() directly to the query builder to save RAM
        $expiring_three_months = NetworkOps::where('contract_auto_renew', 'NO')
            ->whereRaw("DATE_FORMAT(contract_validity, '%m-%d') = ?", [$threeMonthsLater])
            ->count();

        $expired_overall = NetworkOps::whereDate('contract_validity', '<', Carbon::now())->count();
        
        $expiring_current_month = NetworkOps::whereMonth('contract_validity', $currentMonth)->count();

        return response()->json([
            'expiring_three_months'  => $expiring_three_months,
            'expired_overall'        => $expired_overall,
            'expiring_current_month' => $expiring_current_month
        ]);
    }

    public function getClientContracts(): JsonResponse
    {
        $threeMonthsLater = Carbon::now()->addMonths(3)->format('m-d');
        $currentMonth = Carbon::now()->format('m');

        $expiring_three_months = Client::where('contract_auto_renew', 'NO')
            ->whereRaw("DATE_FORMAT(contract_validity, '%m-%d') = ?", [$threeMonthsLater])
            ->count();

        $expired_overall = Client::whereDate('contract_validity', '<', Carbon::now())->count();

        $expiring_current_month = Client::whereMonth('contract_validity', $currentMonth)->count();

        return response()->json([
            'expiring_three_months'  => $expiring_three_months,
            'expired_overall'        => $expired_overall,
            'expiring_current_month' => $expiring_current_month
        ]);
    }
}