<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\EmployeeOffset;
use App\Models\EmployeeOffsetEarning;
use App\Models\EmployeeWfh;
use App\Models\OffsetRemaining;
use App\Models\User;
use App\Notifications\OffsetEarning;
use DateTime;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;
use PHPUnit\Event\Code\Throwable;
use Illuminate\Support\Str;

class EmployeeOffsetEarningController extends Controller
{
    public function index(Request $request)
    {
        //
        $employee = Auth::user();
        
        $keyword = $request->input('keyword', '');
        $perPage = $request->input('per_page',PHP_INT_MAX);
        $sortBy = $request->input('sortBy', '');
        $sortType = $request->input('sortType', '');
        $data = EmployeeOffsetEarning::with([
            'recommending' => fn($recommending) => $recommending->select('employee_id', 'asa_user_id', 'firstname', 'lastname'),
            'approving'=> fn($approving) => $approving->select('employee_id', 'asa_user_id', 'firstname', 'lastname'),
            ])
            ->select(
                'id', 
                'employee_id', 
                'company_id', 
                'dealer_id', 
                'date',
                'from_time',
                'to_time',
                'hours',
                'attachment', 
                'description', 
                'denied_reason', 
                'status', 
                'recommending_id', 
                'allow_higher_approval', 
                'approver_id', 
                'approved_at',
                'recommended_at', 
                'created_at',
                'posted'
            )
            ->where(function ($query) use ($keyword) {
            $keyword = str_replace(" ", "%", $keyword);
            // $query->where('name', 'like', '%' . $keyword . '%');
        });

        if($employee->roles[0]['group_id'] != 1){
            $data->where(['employee_id' => $employee->employee_id]);
        }

        if (!empty($sortBy) && !empty($sortType)) {
            $data = $data->orderBy($sortBy, $sortType);
        }

        $data = $data->paginate($perPage);

        $availableOffset = [];
        $offsetRemaining = [];

        if ($employee->roles[0]['group_id'] != 1) {
            $availableOffset = EmployeeOffsetEarning::where([
                'employee_id' => $employee->employee_id,
                'enabled' => 1
            ])
            ->where('status', '=', '2')
            ->selectRaw('SUM(hours) as total')
            ->groupBy('employee_offset_earnings.hours')
            ->first();

            $offsetRemaining = OffsetRemaining::where([
                'employee_id' => $employee->employee_id,
                'enabled' => 1
            ])
            ->select('remaining')
            ->first();
        }


        $response = [
            'data' => $data,
            'available_offset' => $availableOffset,
            'offset_remaining' => $offsetRemaining
        ];

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

    public function getOffsetEarningList(Request $request)
    {
        //
        $employee = Auth::user();
        
        $keyword = $request->input('keyword', '');
        $perPage = $request->input('per_page',PHP_INT_MAX);
        $sortBy = $request->input('sortBy', '');
        $sortType = $request->input('sortType', '');
        $dealership_id = $request->input('dealership', null);
        
        $data = EmployeeOffsetEarning::with([
            'recommending' => fn($recommending) => $recommending->select('employee_id', 'asa_user_id', 'firstname', 'lastname'),
            'approving'=> fn($approving) => $approving->select('employee_id', 'asa_user_id', 'firstname', 'lastname'),
            'employee'=> fn($employee) => $employee->select('employee_id', 'firstname', 'lastname'),
            ])
            ->select(
                'id', 
                'employee_id', 
                'company_id', 
                'dealer_id', 
                'date',
                'from_time',
                'to_time',
                'hours',
                'attachment', 
                'description', 
                'denied_reason', 
                'status', 
                'validated',
                'validated_by',
                'validated_at',
                'deferred_reason',
                'recommending_id', 
                'allow_higher_approval', 
                'approver_id', 
                'approved_at',
                'recommended_at', 
                'created_at',
                'posted'
            )
            ->where(function ($query) use ($keyword) {
            $keyword = str_replace(" ", "%", $keyword);
            // $query->where('name', 'like', '%' . $keyword . '%');
        });

        if($dealership_id) $data = $data->where('dealer_id', $dealership_id);

        if (!$request->date_created && !$request->range && !$request->status) {
            $data = $data->whereDate('created_at', '>=', now()->subDays(30));
        }
        
        if ($request->date_created) {
            $dates = explode(' to ', $request->date_created); // Split into start and end date
            if (count($dates) == 2) {
                $data = $data->whereBetween('created_at', [$dates[0], $dates[1]]);
            }
        }
        
        if ($request->range) {
            $dates = explode(' to ', $request->range); // Split into start and end date
            if (count($dates) == 2) {
                $data = $data->whereBetween('date', [$dates[0], $dates[1]]);
            }
        }
        
        if ($request->status && is_array($request->status)) {
            $data = $data->where(function ($query) use ($request) {
                if (in_array('pending', $request->status)) {
                    $query->orWhere('status', 0);
                }
        
                if (in_array('validated', $request->status)) {
                    $query->orWhere(function ($q) {
                        $q->where('status', 2)->where('validated', 1);
                    });
                }
        
                if (in_array('denied', $request->status)) {
                    $query->orWhere('status', 99)
                        ->orWhere(function ($q) {
                            $q->where('status', 2)->where('validated', 99);
                        });

                }
        
                if (in_array('for_validation', $request->status)) {
                    $query->orWhere(function ($q) {
                        $q->where('status', 2)->where('validated', 0);
                    });
                }
            });
        }

        $data = $data->paginate(500);

        $response = [
            'data' => $data,
        ];

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

    public function store(Request $request)
    {
        $user = Auth::user();
        
        $validator = Validator::make($request->all(), [
            'date' => "required",
            'from_time' => "required",
        ]);

        /** If validation fails return with error message */
        if ($validator->fails()) {
            $errors = $validator->errors();
            $first = $errors->getMessages();
            return response()->json([
                'status'  => false,
                'message' => (reset($first))[0],
                'errors'  => $errors
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        DB::connection()->beginTransaction();

        try {
            $allow_higher_approval = ($request->allow_higher_approval && $request->allow_higher_approval !== 'null' && $request->allow_higher_approval !== 'false' && trim($request->allow_higher_approval) !== '' ? 1 : 0);
                
            $attachmentName = $this->handleAttachment($request);
            
            $Status = EmployeeOffsetEarning::create([
                'employee_id' => $user->employee_id,
                'company_id' => $user->employees->company_id,
                'dealer_id' => $user->employees->dealer_id,
                'date' => $request->date,
                'from_time' => $request->from_time,
                'to_time' => $request->to_time,
                'hours' => $request->hours,
                'description' => $request->description,
                'attachment' => $attachmentName,
                'recommending_id' => $request->recommending_id,
                'allow_higher_approval' => $allow_higher_approval,
                'approver_id' => $request->approver_id,
                'status' => 0,
            ]);

            // if(!OffsetRemaining::where('employee_id', '=', $user->employee_id)->exists()){
            //     OffsetRemaining::create([
            //         'employee_id' => $user->employee_id,
            //         'company_id' => $user->employees->employee_id,
            //         'remaining' => $request->hours
            //     ]);
            // } else {
            //     $offset = OffsetRemaining::where('employee_id', '=', $user->employee_id)->first();

            //     if ($offset) {
            //         $offset->increment('remaining', $request->hours);
            //     }
            // }

            // dd();

            DB::connection()->commit();

            // Load the relationships
            $Status->load(['employee']);

            // $email_to = $this->getEmployeeEmailData($request->recommending_id);

            // Notification::send($email_to, new OffsetEarning($Status));

            return response()->json([
                'status'  => true,
                'message' => 'Saved successfully!',
                'data'    => $Status
            ],201);

        } catch (\Exception $e) {

            DB::connection()->rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ]);
        }
    }

    public function handleAttachment(Request $request)
    {
        if ($request->hasFile('attachment')) {
            $image = $request->file('attachment');
            $attachmentName = time() . '_' . $image->getClientOriginalName();
            $path = "employee-offset-earning/" . $attachmentName;
            if (Storage::disk('local')->put($path, file_get_contents($image))) {
                return $attachmentName;
            }
            throw new Exception('Unable to process attachment.');
        }
        return '';
    }

    public function update(Request $request)
    {
        // dd($request->all());
        $id = $request->id;

        $data = EmployeeOffsetEarning::where('id', $id)->first();

        $user = Auth::user();
        
        $validator = Validator::make($request->all(), [
            'date' => "required|date",
        ]);

        /** If validation fails return with error message */
        if ($validator->fails()) {
            $errors = $validator->errors();
            $first = $errors->getMessages();
            return response()->json([
                'status'  => false,
                'message' => (reset($first))[0],
                'errors'  => $errors
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        $attachment_name = $request->attachment;

        if($data->attachment != $request->attachment)
        {
            $attachment_file_path = 'employee-offset-earning/' . $data->attachment;
            if(Storage::exists($attachment_file_path))
            {
                Storage::delete($attachment_file_path);
            }

            if($request->hasFile('attachment')) {
                $image      = $request->file('attachment');
                $attachment_name  = time().'_'.$image->getClientOriginalName();
                $path       = "employee-offset-earning/".$attachment_name;
                if(!Storage::disk('local')->put($path, file_get_contents($image)))
                {
                    return response()->json(['message'=> "Failed to upload attachment"],304);
                }
            }
            else
            {
                $attachment_name = null;
            }
        }

        DB::connection()->beginTransaction();

        try {
            $allow_higher_approval = ($request->allow_higher_approval && $request->allow_higher_approval !== 'null' && $request->allow_higher_approval !== 'false' && trim($request->allow_higher_approval) !== '' ? 1 : 0);
            
            $data->employee_id = $user->employee_id;
            $data->hours = $request->hours;
            $data->from_time = $request->from_time;
            $data->to_time = $request->to_time;
            $data->description = $request->description;
            $data->allow_higher_approval = $allow_higher_approval;
            $data->attachment = $attachment_name;
            $data->save();
            
            // $offsetRemaining = OffsetRemaining::where('employee_id', '=', $user->employee_id)->first();            

            // dd($offsetRemaining);

            // if($request->hours > $data->hours){
            //     $hours = $request->hours - $data->hours;
            // }

            DB::connection()->commit();

            return response()->json([
                'status'  => true,
                'message' => 'Saved successfully!',
                'data'    => $data
            ],201);

        } catch (\Exception $e) {

            DB::connection()->rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ]);
        } 
    }

    public function destroy(int $id)
    {
        $data = EmployeeOffsetEarning::find($id);
        if(!$data)
        {
            return response()->json(['message' => "Record not found!"],204);
        }
        DB::connection()->beginTransaction();
        $data->delete();
        DB::connection()->commit();
        return response()->json(['message' => "Record successfully deleted!"],201);
    }

    public function removeAttachment(Request $request)
    {
        $id = $request->id;
        $attachment = $request->attachment;

        $data = EmployeeOffsetEarning::where('id', $id)->first();

        $data->attachment = NULL;

        $data->save();

        DB::connection()->commit();
        
        $attachment_file_path = 'employee-offset-earning/' . $request->attachment;
        if(Storage::exists($attachment_file_path))
        {
            Storage::delete($attachment_file_path);
        }

        return response()->json([
            'status'  => true,
            'message' => 'Saved successfully!',
            'data'    => $data
        ],201);
    }

    public function getEmployeeEmailData($id){
        return User::where('employee_id', '=', $id)->first();
    }

    public function getTitoOrWFH(Request $request){

        $attendance = new EmployeeAttendanceController();

        $timelog = $attendance->getTimelog($request->date, $request->time_keeping_id);
        $wfhRecord = EmployeeWfh::where(['employee_id'=> $request->employee_id, 'date'=>$request->date, 'status'=>2, 'validated'=>1])
                    ->first();
        $schedule = $attendance->getSchedule($request->date, $request->employee_id);
        $ob = $attendance->getOB($request->date, $request->employee_id);

        if($wfhRecord)
        {
            if($schedule){
                if($schedule->schedule->cws != ''){
                    $to_time = $schedule->schedule->cws_to_time;
                    $from_time = $schedule->schedule->cws_from_time;
                } else {
                    $to_time = $schedule->schedule->to_time;
                    $from_time = $schedule->schedule->from_time;
                }

                return response()->json([
                    'from_time' => $from_time,
                    'to_time' => $to_time,
                    'hours' => $wfhRecord->hours >= 8 ? $wfhRecord->hours - 1 : $wfhRecord->hours
                ]);
            }
            
        }
        
        $dayOfWeek = date('l', strtotime($request->date));
        $daysArray = explode(',', $schedule->schedule->day_off);

        if (in_array($dayOfWeek, $daysArray) && $ob) {
            $schedule_out = $schedule->schedule->to_time;

            $time_in = $timelog->filter(fn($tl) => $tl->in_out=='I')->first();
            $time_out = $timelog->filter(fn($tl) => $tl->in_out=='O')->first();

            if($timelog->filter(fn($tl) => $tl->in_out=='I')->isNotEmpty() && $timelog->filter(fn($tl) => $tl->in_out=='O')->isNotEmpty()){

                if(date('H:i:s', strtotime($time_in->datetimelog)) >= $ob->from_time){
                    $time_in = date('H:i:s', strtotime($time_in->datetimelog));
                } else {
                    $time_in = $ob->from_time;
                }

                if(date('H:i:s', strtotime($time_out)) >= $ob->to_time){
                    $time_out = date('H:i:s', strtotime($time_out->datetimelog));
                } else {
                    $time_out = $ob->to_time;
                }

            } else if($timelog->filter(fn($tl) => $tl->in_out=='O')->isNotEmpty() && $timelog->filter(fn($tl) => $tl->in_out=='I')->isEmpty()){
                
                if(date('H:i:s', strtotime($time_out)) >= $ob->to_time){
                    $time_out = date('H:i:s', strtotime($time_out->datetimelog));
                } else {
                    $time_out = $ob->to_time;
                }
                
            } else if($timelog->filter(fn($tl) => $tl->in_out=='O')->isEmpty() && $timelog->filter(fn($tl) => $tl->in_out=='I')->isNotEmpty()){
                
                if(date('H:i:s', strtotime($time_in->datetimelog)) >= $ob->from_time){
                    $time_in = date('H:i:s', strtotime($time_in->datetimelog));
                } else {
                    $time_in = $ob->from_time;
                }
            }

            $schedTimeIn = new DateTime($request->date . ' ' . $time_in);
            $schedTimeOut = new DateTime($request->date . ' ' . $time_out);

            $interval = $schedTimeIn->diff($schedTimeOut);

            return $interval;
        }

        if($timelog && ($timelog->filter(fn($tl) => $tl->in_out=='O')->isNotEmpty() || $ob) && $schedule)
        {
            $dayOfWeek = date('l', strtotime($request->date));
            $daysArray = explode(',', $schedule->schedule->day_off);
            $daysCWSArray = explode(',', $schedule->schedule->cws_day);

            if(in_array($dayOfWeek,$daysCWSArray)) {
                $schedule_out = $schedule->schedule->cws_to_time;
            } elseif(!in_array($dayOfWeek, $daysArray)) {
                $schedule_out = $schedule->schedule->to_time;
            }

            $time_out = $timelog->filter(fn($tl) => $tl->in_out=='O')->first();
            $time_out = $time_out->datetimelog;

            if($ob)
            {
                if($timelog->filter(fn($tl) => $tl->in_out=='O')->isNotEmpty()){
                    $datetime = $timelog->filter(fn($tl) => $tl->in_out=='O')->first();
                    if(date('H:i:s', strtotime($datetime)) <= $ob->to_time){
                        $schedule_out = $datetime;
                    } else {
                        $schedule_out = $ob->to_time;
                    }
                } else {
                    $schedule_out = $ob->to_time;
                }
            }

            $schedule_out_date = new DateTime($request->date . ' ' . $schedule_out);
            $time_out_date = new DateTime($time_out);

            // Calculate the difference
            $interval = $schedule_out_date->diff($time_out_date);

            // Convert to decimal hours
            $decimalHours = $interval->h + ($interval->i / 60) + ($interval->s / 3600);

            // If the difference is negative, make it negative
            if ($interval->invert) {
                $decimalHours *= -1;
            }

            return response()->json([
                'from_time' => date('H:i', strtotime($schedule_out)),
                'to_time' => date('H:i', strtotime($time_out)),
                'hours' => $decimalHours
            ]);

            // return $interval;
        }
    }
}
