<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\Booking;
use App\Models\Gateway;
use App\Models\Location;
use App\Models\LoginActivities;
use App\Models\Space;
use App\Models\Transaction;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;

class DashboardController extends Controller
{
    public function dashboard()
    {
        $transaction = new Transaction;
        $user = User::query();

        $activeUser = User::where('status', 1)->count();
        $disabledUser = User::where('status', 0)->count();

        $totalStaff = Admin::count();

        $latestUser = User::latest()->take(5)->get();

        $totalGateway = Gateway::where('status', true)->count();

        // ============================= Start dashboard statistics =============================================

        $startDate = request()->start_date ? Carbon::createFromDate(request()->start_date) : Carbon::now()->subDays(7);
        $endDate = request()->end_date ? Carbon::createFromDate(request()->end_date) : Carbon::now();
        $dateArray = array_fill_keys(generate_date_range_array($startDate, $endDate), 0);

        $dateFilter = [request()->start_date ? $startDate : $startDate->subDays(1), $endDate->addDays(1)];

        // ============================= End dashboard statistics =============================================

        // set cache for 1 minute
        $loginActivities = Cache::remember('login-activities', 60, function () {
            return LoginActivities::get();
        });

        $browser = $loginActivities->groupBy('browser')->map->count()->toArray();
        $platform = $loginActivities->groupBy('platform')->map->count()->toArray();

        $country = User::all()->groupBy('country')->map(function ($country) {
            return $country->count();
        })->toArray();

        arsort($country);
        $country = array_slice($country, 0, 5);

        $symbol = setting('currency_symbol', 'global');

        // Spaces booking statistics
        $spacesBookingStatistics = Booking::has('space')
            ->selectRaw('space_id, SUM(total_amount) as total_amount')
            ->with('space:id,title')
            ->whereBetween('created_at', $dateFilter)
            ->groupBy('space_id')
            ->get()
            ->map(function ($booking) {
                return $booking->space->title.' - $'.number_format($booking->total_amount, 2);
            });

        $data = [
            'register_user' => $user->count(),
            'active_user' => $activeUser,
            'total_locations' => Location::count(),
            'total_spaces' => Space::count(),
            'total_bookings' => Booking::count(),
            'gateways' => Gateway::count(),
            'disabled_user' => $disabledUser,
            'latest_user' => $latestUser,
            'total_staff' => $totalStaff,
            'date_label' => $dateArray,

            'spaces_booking_statistics' => $spacesBookingStatistics,

            'start_date' => isset(request()->start_date) ? $startDate : $startDate->addDays(1)->format('m/d/Y'),
            'end_date' => isset(request()->end_date) ? $endDate : $endDate->subDays(1)->format('m/d/Y'),
            'total_gateway' => $totalGateway,
            'browser' => $browser,
            'platform' => $platform,
            'country' => $country,
            'symbol' => $symbol,
        ];

        // Date range filter for statistics
        if (request()->ajax()) {

            return response()->json([
                'date_label' => $dateArray,
                'spaces_booking_statistics' => $spacesBookingStatistics,
                'symbol' => $symbol,
            ]);
        }

        return view('backend.dashboard', compact('data'));
    }
}
