<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Controllers\Controller;
use App\Http\Repository\Booking\BookingRepository;
use App\Http\Repository\Dashboard\DashboardRepository;
use App\Models\Booking\SchServiceBooking;
use App\Models\UserManagement\SecUserRole;
use App\Models\Settings\CmnBranch;
use Carbon\Carbon;
use ErrorException;
use Exception;
use Illuminate\Http\Request;

class DashboardController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function home()
    {
        $isMOGAdminOrSysAdmin = SecUserRole::where('sec_user_id', auth()->id())
                                ->where(function ($query) {
                                    $query->whereHas('role', function ($roleQuery) {
                                        $roleQuery->where('name', 'MOG Admin');
                                    })
                                    ->orWhereHas('user', function ($userQuery) {
                                        $userQuery->where('is_sys_adm', 1);
                                    });
                                })
                                ->exists();

        $userRole = auth()->user()->secUserRole->role->name;
        $branches = CmnBranch::where('status', 1)->get();

        return view('dashboard.dashboard', compact('isMOGAdminOrSysAdmin', 'userRole', 'branches'));
    }


    public function getDashboardCommonData(Request $request)
    {
        try {
            $dashboardRepo = new DashboardRepository();
            
            $branchId = $request->get('branchId');

            if ($branchId == 'NaN') {
                $branchId = '';
            }

            $rtrData = [
                'bookingStatus' => $dashboardRepo->getBookingStatus($branchId),
                'incomAndOtherStatistics' => $dashboardRepo->getIncomeAndOtherStatistics($branchId),
                'topService' => $dashboardRepo->getTopServices($branchId),
                'topBranch' => $dashboardRepo->getTopBranch()
            ];
            return $this->apiResponse(['status' => '1', 'data' => $rtrData], 200);
        } catch (Exception $ex) {
            return $this->apiResponse(['status' => '403', 'data' => $ex], 400);
        }
    }

    public function getDashboardMonthlyData(Request $request)
    {
        try {
            $br = new Controller();
            $today = Carbon::now();
            $branchId = ($request->get('branchId') !== '' && $request->get('branchId') !== 'NaN') ? [$request->get('branchId')] : $br->getUserBranch()->pluck('cmn_branch_id')->toArray();
            $allBranches = CmnBranch::where('status', 1)->pluck('id');

            // Get the current month and year
            $month = $today->month;
            $year = $today->year;

            if (!in_array(0, $branchId)) {
                $totalBooking = SchServiceBooking::UserWiseServiceBooking()
                            ->whereMonth('sch_service_bookings.date', $month)
                            ->whereYear('sch_service_bookings.date', $year)
                            ->whereIn('sch_service_bookings.cmn_branch_id', $branchId)
                            ->selectRaw(
                                'sch_service_bookings.status as status,
                                count(sch_service_bookings.status) as serviceCount'
                            )->groupBy('sch_service_bookings.status')->get();
            } else {
                $totalBooking = SchServiceBooking::UserWiseServiceBooking()
                            ->whereMonth('sch_service_bookings.date', $month)
                            ->whereYear('sch_service_bookings.date', $year)
                            ->whereIn('sch_service_bookings.cmn_branch_id', $allBranches)
                            ->selectRaw(
                                'sch_service_bookings.status as status,
                                count(sch_service_bookings.status) as serviceCount'
                            )->groupBy('sch_service_bookings.status')->get();
            }

            $monthlyData = [
                'totalMonthlyBooking' => $totalBooking,
            ];

            return $this->apiResponse(['status' => '1', 'data' => $monthlyData], 200);
        } catch (Exception $ex) {
            return $this->apiResponse(['status' => '403', 'data' => $ex], 400);
        }
    }

    public function getBookingInfo(Request $request)
    {
        try {
            $dashboardRepo = new DashboardRepository();

            if ($request->branchId == 'NaN') {
                $request->branchId = '';
            }

            $rtrData = $dashboardRepo->getBookingInfo($request->serviceStatus, $request->branchId, $request->duration);
            return $this->apiResponse(['status' => '1', 'data' => $rtrData], 200);
        } catch (Exception $ex) {
            return $this->apiResponse(['status' => '403', 'data' => $ex], 400);
        }
    }

    public function changeBookingStatus(Request $request)
    {
        try {
            $bookingRepo = new BookingRepository();
            $rtrData = $bookingRepo->ChangeBookingStatusAndReturnBookingData($request->id, $request->status, 1);
            return $this->apiResponse(['status' => '1', 'data' => $rtrData], 200);
        } catch (ErrorException $ex) {
            return $this->apiResponse(['status' => '-501', 'data' => $ex->getMessage()], 400);
        } catch (Exception $ex) {
            return $this->apiResponse(['status' => '501', 'data' => $ex], 400);
        }
    }
}
