<?php

namespace App\Http\Controllers\Backend;

use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Services\Task\TaskService;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Support\Facades\Auth;
use Modules\Break\Entities\UserBreak;
use App\Models\Hrm\Leave\LeaveRequest;
use App\Models\Hrm\Attendance\Attendance;
use App\Repositories\DashboardRepository;
use App\Services\Management\ProjectService;
use App\Repositories\Hrm\Payroll\SalaryRepository;
use App\Repositories\Hrm\Finance\ExpenseRepository;
use Modules\SpecialAttendance\Entities\DutyCalendar;
use App\Repositories\Hrm\Expense\HrmExpenseRepository;
use App\Repositories\Hrm\Attendance\AttendanceRepository;
use App\Repositories\Hrm\Department\DepartmentRepository;


class DashboardController extends Controller
{
    protected $dashboardRepository;
    protected $attendanceRepo;
    protected $expenseRepo;
    protected $expenseNewRepo;
    protected $departmentRepo;
    protected $salaryRepository;
    protected $taskService;
    protected $projectService;



    public function __construct(
        DashboardRepository $dashboardRepository,
        AttendanceRepository $attendanceRepo,
        HrmExpenseRepository $expenseRepo,
        ExpenseRepository $expenseNewRepo,
        DepartmentRepository $departmentRepo,
        SalaryRepository $salaryRepository,
        TaskService $taskService,
        ProjectService $projectService
    ) {
        $this->dashboardRepository = $dashboardRepository;
        $this->attendanceRepo = $attendanceRepo;
        $this->expenseRepo = $expenseRepo;
        $this->expenseNewRepo = $expenseNewRepo;
        $this->departmentRepo = $departmentRepo;
        $this->salaryRepository = $salaryRepository;
        $this->taskService = $taskService;
        $this->projectService = $projectService;
    }

    public function loadMyProfileDashboard($request)
    {
        try {
            $today = Carbon::now()->toDateString();
            $request['month'] = date('Y-m');

            $currentMonthAttendance = Attendance::with('breaks', 'dutyCalendar.dutySchedule')->where('user_id', Auth::id())
                ->whereMonth('date', Carbon::now()->month)
                ->whereYear('date', Carbon::now()->year)
                ->get();

            $currentMonthDutyCalendar = DutyCalendar::with('attendance')->where('employee_id', Auth::id())
                ->whereDate('date', '<=', Carbon::now()->toDateString())
                ->whereMonth('date', Carbon::now()->month)
                ->whereYear('date', Carbon::now()->year)
                ->where('is_weekend', '!=', 1)
                ->get();

            $data['in_time_attendance'] = 0;
            $data['late_attendance'] = 0;
            $data['leave_days'] = count($currentMonthDutyCalendar->where('leave_id', '!=', null));
            $data['absent_days'] = 0;

            foreach ($currentMonthDutyCalendar->whereNotNull('duty_schedule_id') as $key => $dutyCalendar) {

                if ($dutyCalendar->attendance && lateCheckinCheck($dutyCalendar->dutySchedule->start_time, main_time_format($dutyCalendar->attendance->check_in), $dutyCalendar->dutySchedule->consider_time, $dutyCalendar->dutySchedule->end_on_same_date)) {
                    $data['late_attendance'] = +1;
                } elseif ($dutyCalendar->attendance) {
                    $data['in_time_attendance'] = +1;
                } else {
                    $data['absent_days'] = +1;
                }
            }

            $totalWorkedTime = Attendance::select(DB::raw('SUM(TIME_TO_SEC(TIMEDIFF(check_out, check_in))) AS total_seconds'))
                ->where('user_id', Auth::id())
                ->whereMonth('date', Carbon::now()->month)
                ->whereYear('date', Carbon::now()->year)
                ->whereNotNull('check_in')
                ->whereNotNull('check_out')
                ->first();

            $data['totalWorkedHours'] = ($totalWorkedTime->total_seconds ?? 0) / 3600;
            $data['currentMonthDutySchedules'] = DutyCalendar::whereHas('dutySchedule')->with('dutySchedule')->where('employee_id', Auth::id())->whereMonth('date', Carbon::now()->month)
                ->whereYear('date', Carbon::now()->year)->get();

            $data['currentMonthTotalHours'] = $data['currentMonthDutySchedules']->sum(function ($dutyCalendar) {
                return $dutyCalendar->dutySchedule->hour;
            });

            $data['currentMonthBreaks'] = UserBreak::where('user_id', Auth::id())->whereMonth('date', Carbon::now()->month)->whereYear('date', Carbon::now()->year)->get();

            $todayAttendance = $currentMonthAttendance->filter(function ($attendance) use ($today) {
                return $attendance->date === $today;
            });

            $todaySchedule = $data['currentMonthDutySchedules']->filter(function ($schedule) use ($today) {
                return $schedule->date === $today;
            })->first();

            $data['todayAttendance'] = $todayAttendance->first();
            $data['todayTotalHours'] = @$todaySchedule->dutySchedule->hour;
            $data['currentMonthAttendance'] = $currentMonthAttendance;

            $data['totalMonthlyLateTime'] = 0;
            $data['todayLateTime'] = null;
            foreach ($currentMonthAttendance as $attendance) {
                if (isset($attendance->dutyCalendar->dutySchedule)) {
                    $late = lateCheckInHours($attendance->dutyCalendar->dutySchedule->start_time, $attendance->check_in);
                    $data['totalMonthlyLateTime'] += $late;
                    if ($attendance->dutyCalendar->date == $today) {
                        $data['todayLateTime'] = lateCheckInHours($attendance->dutyCalendar->dutySchedule->start_time, $attendance->check_in);
                    }
                }
            }

            $data['assignLeaves'] = Auth::user()->assignLeave;
            $data['leaveRequests'] = Auth::user()->leaveRequests;
            $data['currentMonthLeave'] = $data['leaveRequests']->filter(function ($leaveRequest) {
                return $leaveRequest->status_id == 1 && Carbon::parse($leaveRequest->date)->month == Carbon::now()->month;
            })->count();

            return $returnHTML = view('backend.dashboard.load_my_dashboard', compact('data'))->render();
            return $returnHTML = view('backend.dashboard.loadProfileDashboard', compact('data'))->render();
        } catch (\Throwable $th) {
            return $th->getMessage();
        }
    }

    public function loadCompanyDashboard($request)
    {
        try {
            $today = Carbon::now()->toDateString();
            $request['month'] = date('Y-m');

            $menus = $this->dashboardRepository->getNewCompanyDashboardStatistics($request);
            $data['dashboardMenus'] = @$menus->original['data'];

            $data['totalPendingLeaves'] = LeaveRequest::where('status_id', 2)->count();

            $data['earlyLeave'] = Attendance::whereDate('date', Carbon::now()->toDateString())
            ->whereNotNull('check_out')->where('out_status', 'LE')->count();

            $data['earlyLeave'] = Attendance::whereDate('date', Carbon::now()->toDateString())
            ->whereNotNull('check_in')->where('in_status', 'OT')->count();

            $data['todayLate'] = Attendance::whereDate('date', Carbon::now()->toDateString())
            ->whereNotNull('check_in')->where('in_status', 'L')->count();

            $data['todayAbsents'] = DutyCalendar::whereDate('date', Carbon::now()->toDateString())
            ->where('is_weekend', '!=', 1)
            ->doesntHave('attendance')
            ->count();

            $data['todayPresents'] = DutyCalendar::whereDate('date', Carbon::now()->toDateString())
            ->where('is_weekend', '!=', 1)
            ->whereHas('attendance')
            ->count();

            return $returnHTML = view('backend.dashboard.load_company_dashboard', compact('data'))->render();
        } catch (\Throwable $th) {
            return $th->getMessage();
        }
    }

    public function loadSuperadminDashboard($request)
    {
        try {
            $request['month'] = date('Y-m');
            $menus = $this->dashboardRepository->getDashboardStatistics($request);
            $data['dashboardMenus'] = @$menus->original['data'];
            $companyMenus = $this->dashboardRepository->getCompanyDashboardStatistics($request);
            $data['companyMenus'] = @$companyMenus->original['data'];
            return $returnHTML = view('backend.dashboard.loadSuperadminDashboard', compact('data'))->render();
        } catch (\Throwable $th) {
            return $th->getMessage();
        }
    }

    public function profileWiseDashboard(Request $request)
    {
        try {
            $user = Auth::user();
            $dashboard = '';
            $date = date('Y-m-d');
    
            switch ($request->dashboardType) {
                case 'My Dashboard':
                    $dashboard             = $this->loadMyProfileDashboard($request);
                    $data['dashboardType'] = 'Dashboard';
                    $data['appointment']   = $this->dashboardRepository->getAppointmentDashboard(auth()->id());
                    $data['meeting']       = $this->dashboardRepository->getMeetingDashboard(auth()->id());
                    break;
                case 'Company Dashboard':
                    $dashboard                 = $this->loadCompanyDashboard($request);
                    $data['dashboardType']     = 'Company Dashboard';
                    $data['expense']           = $this->expenseNewRepo->getMonthlyExpense($request);
                    $data['appointment']       = $this->dashboardRepository->getAppointmentDashboard();
                    $data['meeting']           = $this->dashboardRepository->getMeetingDashboard();
                    $data['today_absent']      = $this->dashboardRepository->todayAbsentEmployee();
                    $data['today_late']        = $this->dashboardRepository->todayLateAttendance();
                    $data['today_early_leave'] = $this->dashboardRepository->todayEarlyLeave();
    
                    break;
                case 'Superadmin Dashboard':
                    $dashboard = $this->loadSuperadminDashboard($request);
                    $data['dashboardType'] = 'Super Admin';
                    break;
            }

            $data['dashboard'] = $dashboard;
            $data['status'] = 'success';
            $data['message'] = 'Dashboard loaded successfully';
    
            return $data;
        } catch (\Throwable $th) {
            info($th->getMessage());
        }
    }

    public function companyDashboard()
    {
        $request['month'] = date('Y-m');
        $menus = $this->dashboardRepository->getDashboardStatistics($request);
        $data['dashboardMenus'] = @$menus->original['data'];
        $companyMenus = $this->dashboardRepository->getCompanyDashboardStatistics($request);
        $data['companyMenus'] = @$companyMenus->original['data'];
        $attendance_data = $this->attendanceRepo->getCheckInCheckoutStatus(auth()->user()->id);
        $data['attendance'] = @$attendance_data->original['data'];
        $company_today_attendance = $this->attendanceRepo->getTodayAttendance(date('Y-m-d'));
        $data['company_today_attendance'] = $company_today_attendance;

        return $data;
    }

    public function superadminDashboard()
    {
        $request['month'] = date('Y-m');
        $menus = $this->dashboardRepository->getSuperadminDashboardStatistic($request);
        $data['dashboardMenus'] = @$menus->original['data'];


        return $data;
    }

    public function index(Request $request)
    {
        if(isMainCompany()){
            return redirect()->route('saas.dashboard');
        } 

        if (
            !isMainCompany() && 
            config('app.mood') == 'Saas' && 
            isModuleActive('Saas') && 
            checkSingleCompanyIsDeactivated()
        ) {
            return redirect()->route('single-company.deactivated');
        }

        try {
            // if (auth()->user()->role_id == 1) {
            //     $data = $this->superadminDashboard();
            //     return view('backend.__superadmin_dashboard', compact('data'));
            // } else {
                if (!config('settings.app')['site_under_maintenance']) {

                    $data = $this->companyDashboard();
                    return view('backend.dashboard', compact('data'));
                } else {
                    return redirect('/');
                }
            // }
        } catch (\Exception $e) {
            Toastr::error(_trans('response.Something went wrong!'), 'Error');
            return redirect()->back();
        }
    }


    public function currentMonthPieChart(Request $request)
    {
        $request['month'] = date('Y-m');
        return $this->expenseRepo->getMonthlyExpense();
    }

    public function incomeExpenseGraph(Request $request)
    {
        try {
            return $this->dashboardRepository->getIncomeExpenseGraph($request);
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    public function statistics(Request $request)
    {
        try {
            return $this->dashboardRepository->getDashboardStatistics($request);
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    public function logout(Request $request)
    {
        Auth::logout();
        return redirect()->route('adminLogin');
    }
}
