<?php

namespace App\Helpers;

use App\Models\Candidate;
use App\Models\User;
use App\Models\UserTimeline;
use Carbon\Carbon;
use App\Models\Batch;
use App\Models\Classes;
use App\Models\Address;
class AdminHelper
{


    public static function leadManagementTAT($user_id, $stage, $createdDate)
    {
        $instance = new self();

        if ($stage == "Admitted") {
            return "<p class='tat'>--</p>";
        }
        $stagesCategory = [
            "Inquiry" => "Inquiry",
            "Counselling" => "Inquiry",
            "University to be suggested" => "Inquiry",
            "Universities suggested" => "Inquiry",
            "Application ready to submit" => "Application",
        ];



        $stageTatArray = [
            "Inquiry" => ["day" => 0, "tat" => 5],
            "Counselling" => ["day" => 5, "tat" => 1],

            "University to be suggested" => ["day" => 6, "tat" => 1],
            "Universities suggested" => ["day" => 6, "tat" => 1],

            "Application ready to submit" => ["day" => 7, "tat" => 2],

            "Application submitted" => ["day" => 9, "tat" => 15],

            "Application Rejected" => ["day" => 24, "tat" => 1],

            "Offer Issued" => ["day" => 24, "tat" => 3],

            "Offer Accepted" => ["day" => 27, "tat" => 15],
            "Offer Rejected" => ["day" => 27, "tat" => 3],

            "Admission Letter Pending" => ["day" => 42, "tat" => 15],

            "Initial Fee / Tuition Fee Deposit" => ["day" => 57, "tat" => 15],
            "Admitted" => ["day" => 57, "tat" => 15],

            "Visa In Process" => ["day" => 72, "tat" => 2],
            "Visa Accepted" => ["day" => 74, "tat" => 45],
            "Visa Rejected" => ["day" => 74, "tat" => 45],


            // "Work Visa" => ["day"=>118,"tat"=>0],
            // "Student backed out / Dropped" => ["day"=>0,"tat"=>0],
            // "Test Preparation" => ["day"=>0,"tat"=>0],
            // "Student Defered" => ["day"=>0,"tat"=>0],




        ];

        $stages = $stageTatArray[$stage] ?? null;



        $currentDate = Carbon::parse($createdDate);
        $lead_created_business_working_day =    $instance->calculateBusinessDaysDifference($currentDate); // Lead creatation 
        if (!empty($stages)) {
            $currentUserTimelineDate =    $instance->getUserTimelineDate($user_id, $stage);

            $stage_tat = $stages["tat"];
            $stage_tat_day = $stages["day"];
            if ($stage == "Inquiry") {

                // $currentSatageWorkingDay =  $instance->calculateBusinessDaysDifference($currentUserTimelineDate);

                $stage_tat_diffrence = (int)$stage_tat_day - (int)$lead_created_business_working_day + $stage_tat;


                $tat_html = '<p class="tat">' . $lead_created_business_working_day;

                $tat_class = 'red';
                if ($stage_tat_diffrence > 0) {
                    $tat_class = 'green';
                } else if ($stage_tat_diffrence == 0) {
                    $tat_class = 'orange';
                }
                if ($tat_class != "green") {
                    $tat_html .= "&nbsp;<span class='tat-value $tat_class'> (" . $stage_tat_diffrence . ")</span>";
                }

                return $tat_html;
            } elseif (!empty($currentUserTimelineDate)) {

                // $currentSatageWorkingDay =  $instance->calculateBusinessDaysDifference($currentUserTimelineDate);

                // $stage_tat_diffrence = (int)$stage_tat_day - (int)$lead_created_business_working_day+$stage_tat;


                // $tat_html = '<p class="tat">'.$lead_created_business_working_day;

                // $tat_class = 'red';
                // if($stage_tat_diffrence > 0){
                //     $tat_class = 'green';
                // }else if($stage_tat_diffrence == 0){
                //     $tat_class = 'orange';
                // }

                // $tat_html .= "&nbsp;<span class='tat-value $tat_class'> (".$stage_tat_diffrence.")</span>";

                // return $tat_html;

                $temp_stage_tat_diffrence = (int)$stage_tat_day - (int)$lead_created_business_working_day;

                $stage_tat_diffrence = (int)$stage_tat_day - (int)$lead_created_business_working_day + $stage_tat;

                $tat_html = '<p class="tat">' . $lead_created_business_working_day;
                $show_tat = $stage_tat_diffrence;
                $tat_class = 'red';

                if ($stage_tat_diffrence >= 0 && $temp_stage_tat_diffrence < 0) {
                    $tat_class = 'orange';
                    $show_tat = "-";
                } else if ($stage_tat_diffrence > 0) {
                    $tat_class = 'green';
                    $show_tat = $temp_stage_tat_diffrence;
                }

                $tat_html .= "&nbsp;<span class='tat-value $tat_class'> (" . $show_tat . ")</span>";

                return $tat_html;
            } else {
                return "<p class='tat'>$lead_created_business_working_day</p>";
            }
        } else {
            return "<p class='tat'>$lead_created_business_working_day</p>";
        }
    }


    public static function getTATDays($user_id, $stage, $createdDate)
    {
        $instance = new self();
        $stageTatArray = [
            "Inquiry" => ["day" => 0, "tat" => 5],
            "Counselling" => ["day" => 5, "tat" => 1],

            "University to be suggested" => ["day" => 6, "tat" => 1],
            "Universities suggested" => ["day" => 6, "tat" => 1],

            "Application ready to submit" => ["day" => 7, "tat" => 2],

            "Application submitted" => ["day" => 9, "tat" => 15],

            "Application Rejected" => ["day" => 24, "tat" => 1],

            "Offer Issued" => ["day" => 24, "tat" => 3],

            "Offer Accepted" => ["day" => 27, "tat" => 15],
            "Offer Rejected" => ["day" => 27, "tat" => 3],

            "Admission Letter Pending" => ["day" => 42, "tat" => 15],

            "Initial Fee / Tuition Fee Deposit" => ["day" => 57, "tat" => 15],
            "Admitted" => ["day" => 57, "tat" => 15],

            "Visa In Process" => ["day" => 72, "tat" => 2],
            "Visa Accepted" => ["day" => 74, "tat" => 45],
            "Visa Rejected" => ["day" => 74, "tat" => 45],


            // "Work Visa" => ["day"=>118,"tat"=>0],
            // "Student backed out / Dropped" => ["day"=>0,"tat"=>0],
            // "Test Preparation" => ["day"=>0,"tat"=>0],
            // "Student Defered" => ["day"=>0,"tat"=>0],


        ];

        $stages = $stageTatArray[$stage] ?? null;




        $currentDate = Carbon::parse($createdDate);
        $lead_created_business_working_day =    $instance->calculateBusinessDaysDifference($currentDate); // Lead creatation 
        if (!empty($stages)) {
            // $currentUserTimelineDate =    $instance->getUserTimelineDate($user_id, $stage);
            $stage_tat = $stages["tat"];
            $stage_tat_day = $stages["day"];

            // $stage_tat_diffrence = (int)$stage_tat_day - (int)$lead_created_business_working_day+$stage_tat;

            // return $stage_tat_diffrence;

            $temp_stage_tat_diffrence = (int)$stage_tat_day - (int)$lead_created_business_working_day;

            $stage_tat_diffrence = (int)$stage_tat_day - (int)$lead_created_business_working_day + $stage_tat;

            $show_tat = $stage_tat_diffrence;

            if ($stage_tat_diffrence >= 0 && $temp_stage_tat_diffrence < 0) {
                $show_tat = null;
            } else if ($stage_tat_diffrence > 0) {
                $show_tat = $temp_stage_tat_diffrence;
            }
          
            return $show_tat;
        }
        return null;
    }

    function calculateBusinessDaysDifference($userTimelineDate, $currentDateTime = null)
    {
        if (!empty($currentDateTime)) {
            $currentDateTime = Carbon::parse($currentDateTime);
        } else {
            $currentDateTime = Carbon::now();
        }

        $userTimelineDate = Carbon::parse($userTimelineDate);

        $daysDifference = 0;
        $currentDate = $userTimelineDate->copy();

        while ($currentDate <= $currentDateTime) {
            if ($currentDate->dayOfWeek != Carbon::SUNDAY) {
                $daysDifference++;
            }
            $currentDate->addDay();
        }

        return $daysDifference;
    }


    function calculateBusinessHoursDifference($userTimelineDate)
    {
        $startDateTime = Carbon::parse($userTimelineDate);
        $endDateTime = Carbon::now();

        // Set working hours (9 AM to 7 PM)
        $startWorkingHour = 9;
        $endWorkingHour = 19;

        // Ensure the start date is within working hours
        $startDateTime->hour = max($startDateTime->hour, $startWorkingHour);

        // Ensure the end date is within working hours
        $endDateTime->hour = min($endDateTime->hour, $endWorkingHour);

        // Calculate the total business hours difference
        $businessHoursDifference = $startDateTime->diffInHours($endDateTime, false, function (Carbon $date) use ($startWorkingHour, $endWorkingHour) {
            return $date->dayOfWeek !== Carbon::SUNDAY && $date->hour >= $startWorkingHour && $date->hour < $endWorkingHour;
        });

        return $businessHoursDifference;
    }

    // function calculateBusinessHoursDifference($userTimelineDate)
    // {
    //     $startDateTime = Carbon::parse($userTimelineDate);
    //     $endDateTime = Carbon::now();

    //     $hoursDifference = $startDateTime->diffInHours($endDateTime);

    //     return $hoursDifference;
    // }

    function getUserTimelineDate($user_id, $stage)
    {
        return UserTimeline::where('user_id', $user_id)
            ->where('stages', $stage)
            ->orderBy('created_at', 'desc')
            ->pluck('created_at')
            ->first();
    }


    public static function allTatUpdates()
    {
        try {
            $instance = new self();
            $users = User::whereNull('deleted_at')
                ->whereNotNull('stages')
                ->whereNotIn('stages', ['Admitted', 'Student backed out / Dropped'])
                ->select('id', 'stages', 'created_at')
                ->with('timeLine:id,user_id,event')
                ->get();



            foreach ($users as $user) {
                $tat = $instance->getTATDays($user->id, $user->stages, $user->created_at);
                $user->update(['TAT' => $tat]);
            }

            return true;

            // foreach ($users as $user) {
            //     $tat = $instance->getTATDays($user->id, $user->stages, $user->created_at);

            //     // Get the event with 'event' equal to 0
            //     $eventWithZero = NULL;
            //     $eventWithZero = $user->timeLine->where('event', 0)->first();

            //     if ($user->timeLine->isNotEmpty() && $eventWithZero) {
            //         // Update the TAT of the event with 'event' equal to 0
            //         $eventWithZero->update(['TAT' => $tat]);
            //     }

            //     // Update the user's overall TAT
            //     $user->update(['TAT' => $tat]);
            // }

            // foreach ($users as $user) {
            //     $tat =  $instance->getTATDays($user->id, $user->stages, $user->created_at);
            //     if ($user->timeLine->isNotEmpty() && $user->timeLine->where('event',0)->first()) {
            //         $user->timeLine->where('event',0)->first()->update(['TAT' => $tat]);
            //     }

            //     $user->update(['TAT' => $tat]);
            // }

        } catch (\Throwable $th) {
            return false;
        }
    }



    function isIndianNationalHoliday($date) {
        $year = $date->format('Y');
    
        // List of recurring national holidays
        $recurringHolidays = array(
            '01-26', // Republic Day
            '08-15', // Independence Day
            // Add more holidays as needed
        );
    
        // Calculate dynamic dates for recurring holidays
        $dynamicHolidays = array_map(function ($holiday) use ($year) {
            return sprintf('%d-%s', $year, $holiday);
        }, $recurringHolidays);
    
        return in_array($date->format('Y-m-d'), $dynamicHolidays);
    }


    function getNextWorkingDay($date) {
        $instance = new self();
        $nextDay = $date->addDay();
    
        // Loop until a valid working day is found, skipping national holidays
        while ($nextDay->format('N') == 7 ||   $instance->isIndianNationalHoliday($nextDay)) {
            if ( $instance->isIndianNationalHoliday($nextDay)) {
                $nextDay->addDay(); // Skip the national holiday
            } else {
                $nextDay->addDay(); // Move to the next day if it's a Sunday
            }
        }
    
        return $nextDay;
    }

    function getClassCode($batch_id) {
        $batch = Batch::withTrashed()->find($batch_id);
       if(!empty($batch)){
        $classCode =  $batch->batch_code . "Cl00" . ($batch->number_of_classes + 1);
        $existingclassCode = Classes::where('class_code', $classCode)->exists();
    
        while ($existingclassCode) {
            $code = rand(1000, 10000);
            $classCode =  $batch->batch_code . "Cl00". $code . ($batch->number_of_classes + 1);
            $existingclassCode = Classes::where('class_code', $classCode)->exists();
        }

         return $classCode;
       }else{
        return null;
       }
    
       
    }

  

    function getBatchCode($address_id) {
        // Retrieve city name based on the provided address_id (assuming you have a model for addresses)
        // dd($address_id);
        $address = Address::find($address_id);

        if (!empty($address)) {
            $cityName = $address->city;
            
            if (!empty($cityName)) {
                // Use the first three letters of the city name as part of the code
                $randomLetters = strtoupper(substr($cityName, 0, 3));
            } else {
                // If city name is empty, generate random 3-letter code
                $randomLetters = strtoupper(substr(str_shuffle('abcdefghijklmnopqrstuvwxyz'), 0, 3));
            }
        
            $officeCode = $address->id;
        
            // Generate a unique timestamp
            $timestamp = date('YmdHis');
            $last_five = substr($timestamp, -5);
            $timestamp =  $last_five;
        
            // Concatenate the components to form the batch code
            $code = $randomLetters . $officeCode . 'A' . $timestamp;
    
            // Check if the generated batch code already exists
            $existingCode = Batch::where('batch_code', $code)->exists();
    
            // If the generated batch code already exists, generate a new one until it's unique
            while ($existingCode) {
                // Generate a new timestamp
                $timestamp = date('YmdHis');
                $last_five = substr($timestamp, -5);
                $timestamp =  $last_five;
            
                // Concatenate the components to form the new batch code
                $code = $randomLetters . $officeCode . 'A' . $timestamp;
               
                // Check again if the new batch code already exists
                $existingCode = Batch::where('batch_code', $code)->exists();
            }
            return $code;
        } else {
            return null;
        }
    }
    

    
}
