<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\EmployeeTimeAdjustment;
use App\Models\NotificationErrorLog;
use App\Models\User;
use App\Notifications\TimeAdjustment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Notification;
use Throwable;

class TimeAdjustmentApprovalController extends Controller
{
    public function index(Request $request)
    {
        $employee = Auth::user();

        DB::enableQueryLog();

        $keyword = $request->input('keyword', '');
        $perPage = $request->input('per_page', PHP_INT_MAX);
        $sortBy = $request->input('sortBy', '');
        $sortType = $request->input('sortType', '');

        $currentEmp = $employee->employees ? $employee->employees->employee_id : '';
        
        $data = EmployeeTimeAdjustment::with(['recommending', 'approving', 'employee'])
            ->where(function ($query) use ($employee) {
                $query->where('recommending_id', $employee->employees ? $employee->employees->employee_id : '')
                    ->orWhere('approver_id', $employee->employees ? $employee->employees->employee_id : '');
            })
            ->where('enabled', 1)
            ->whereNull('deleted_at')
            ->select('employee_time_adjustments.*')
            ->selectRaw('
                (
                    SELECT COUNT(*) FROM employee_time_adjustments AS el 
                    WHERE el.deleted_at IS NULL
                    AND (el.status IN (0, 1) OR (el.status = 2 AND el.validated = 0)) 
                    AND (el.recommending_id = '.$currentEmp.' OR el.approver_id = '.$currentEmp.') 
                    AND el.deleted_at IS NULL
                ) AS pending,
                (
                    SELECT COUNT(*) FROM employee_time_adjustments AS el 
                    WHERE el.deleted_at IS NULL
                    AND el.status = 2 AND el.validated = 1
                    AND (el.recommending_id = '.$currentEmp.' OR el.approver_id = '.$currentEmp.') 
                    AND el.deleted_at IS NULL
                ) AS approved,
                (
                    SELECT COUNT(*) FROM employee_time_adjustments AS el
                    WHERE el.deleted_at IS NULL 
                    AND el.status = 99 
                    AND (el.recommending_id = '.$currentEmp.' OR el.approver_id = '.$currentEmp.') 
                    AND el.deleted_at IS NULL
                ) AS denied
            ');

            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_from', [$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(function ($q) {
                            $q->where('status', 0)->orWhere('status', 1);
                        });
                    }
                    
                    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(function ($q) {
                            $q->where('status', 99)
                                ->orWhere(function ($q2) {
                                    $q2->where('status', 2)->where('validated', 99);
                                });
                        });
                    }
                    
                    if (in_array('for_validation', $request->status)) {
                        $query->orWhere(function ($q) {
                            $q->where('status', 2)->where('validated', 0);
                        });
                    }
                });
            } else {
                $data = $data->where('status', '!=', 99)
                    ->where('status', '!=', 2)
                    ->where('validated', '!=', 1);
            }

            $data = $data->orderBy('created_at', 'DESC')->get();

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

    public function update(Request $request, int $id)
    {
        $data = EmployeeTimeAdjustment::with(['employee'])->where('id', $id)->first();

        if (!$data) {
            return response()->json(['messages' => 'No data found.'], 404);
        }

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

        try {
            $now = date('Y-m-d H:i:s');

            ($request->status == 2 ? $request['approved_at'] = $now : $request->status == 1)
             ? $request['recommended_at'] = $now : '';

            $data->fill($request->all());

            $data->save();

            $data->touch();

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

            $employee_id_for_notification = $request->status == 1 ? $data->approver_id : $data->employee_id;

            $email_to = $this->getEmployeeEmailData($employee_id_for_notification);

            try {
                if ($email_to) {
                    Notification::send($email_to, new TimeAdjustment($data));
                    
                } else {

                    try {
                        $error = [
                            'user_id' => Auth::id(),
                            'model' => 'App\Model\EmployeeTimeAdjustment',
                            'message' => 'Email To Not Found'
                        ];
                        
                        $data = NotificationErrorLog::create($error);
                
                        DB::connection()->commit();

                    } catch (Throwable $e) {
                        DB::connection()->rollback();
                    }
                }

            } catch (\Exception $e) {
                try {
                    $error = [
                        'user_id' => Auth::id(),
                        'model' => 'App\Model\EmployeeTimeAdjustment',
                        'message' => $e->getMessage()
                    ];
                    
                    $data = NotificationErrorLog::create($error);
            
                    DB::connection()->commit();

                } catch (Throwable $e) {
                    DB::connection()->rollback();

                }
            }

            return response()->json([
                'message' => 'Record Successfully updated!',
                'status' => 'success',
                'data' => $data,
            ],201);

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

    public function updateApprover(Request $request, int $id)
    {

        $data = EmployeeTimeAdjustment::with(['employee'])->where('id', $id)->first();

        if (!$data) {
            return response()->json(['messages' => 'No data found.'], 404);
        }

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

        try {

            $employee_id_for_notification = [];
            
            if($request->recommending_id != $data->recommending_id){
                $employee_id_for_notification[] = $request->recommending_id;
            } 
            
            if ($request->approver_id != $data->approver_id){
                $employee_id_for_notification[] = $request->approver_id;
            }

            foreach($employee_id_for_notification as $employee_id){
                
                $email_to = $this->getEmployeeEmailData($employee_id);

                try {
                    if ($email_to) {
                        Notification::send($email_to, new TimeAdjustment($data));
                    } else {

                        try {
                            $error = [
                                'user_id' => Auth::id(),
                                'model' => 'App\Model\EmployeeTimeAdjustment',
                                'message' => 'Email To Not Found'
                            ];
                            
                            $data = NotificationErrorLog::create($error);
                    
                            DB::connection()->commit();

                        } catch (Throwable $e) {
                            DB::connection()->rollback();

                        }
                    }
                } catch (\Exception $e) {
                    try {
                        $error = [
                            'user_id' => Auth::id(),
                            'model' => 'App\Model\EmployeeTimeAdjustment',
                            'message' => $e->getMessage()
                        ];
                        
                        $data = NotificationErrorLog::create($error);
                
                        DB::connection()->commit();

                    } catch (Throwable $e) {
                        DB::connection()->rollback();

                    }
                }
            }

            $data->fill($request->all());

            $data->save();

            $data->touch();

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

            return response()->json([
                'message' => 'Record Successfully updated!',
                'status' => 'success',
                'data' => $data,
            ],201);

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

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

    public function HrValidation(Request $request,int $id){
        $status = $request->status;
        $data = EmployeeTimeAdjustment::with(['employee'])->where('id', $id)->first();
        if(!$data){
            return response()->json(['messages' => 'No data found.']);
        }
        $employee_id  =Auth::user()->employees->employee_id;
        
        DB::beginTransaction();
        try{
            $data->validated_by = $employee_id;
            $data->validated_at = now();
            $data->validated = $status;
            $data->deferred_reason = $request->reason;
            $data->save();
            $email_to = $this->getEmployeeEmailData($employee_id);

            // try{
            //     if($email_to != ''){
            //         Notification::send($email_to, new TimeAdjustment($data));
            //     }
            // } catch (Throwable $e) {
            //     // Log the error or handle it as needed
            //     // For this example, we'll just ignore email sending failures
            //     $this->logNotificationError('Failed to send HR validation notification: ' . $e->getMessage());
            // }
            
            DB::commit();
            return response()->json([
                'message' => 'Record Successfully updated!',
                'status' => 'success',
                'data' => $data,
            ], 201);
        } catch (Throwable $e) {
            DB::rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ]);
        }
        
    }

    private function logNotificationError($message)
    {
        try {
            NotificationErrorLog::create([
                'user_id' => Auth::id(),
                'model' => 'App\Model\EmployeeLeave',
                'message' => $message
            ]);
            DB::commit();
        } catch (Throwable $e) {
            DB::rollback();
        }
    }
}
