<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\EmployeeLeave;
use App\Models\EmployeeLeaveCredits;
use App\Models\EmployeeOb;
use App\Models\EmployeeOffset;
use App\Models\EmployeeOffsetEarning;
use App\Models\EmployeeOvertime;
use App\Models\EmployeeTimeAdjustment;
use App\Models\EmployeeUndertime;
use App\Models\LeaveLedger;
use App\Models\NotificationErrorLog;
use App\Models\OffsetRemaining;
use App\Models\User;
use App\Notifications\Leave;
use App\Notifications\OffsetAvailment;
use App\Notifications\OffsetEarning;
use App\Notifications\Overtime;
use App\Notifications\TimeAdjustment;
use App\Notifications\Travel;
use App\Notifications\Undertime;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Notification;
use Throwable;

class ApproveAttendanceRequestsMobileController extends Controller
{
    public function approve_leave_request(Request $request)
    {
        $data = EmployeeLeave::with(['employee', 'leave_type'])->where('id', $request->id)->first();
        
        if (!$data) {
            return response()->json(['messages' => 'No data found.'], 404);
        }

        if($data->recommending_id != $request->officer_id && $data->approver_id != $request->officer_id){
            return response()->json(['messages' => 'You are not the recommending or approving officer of this record.'], 404);
        }

        if($request->status == 99){
            if($data->leave_id != 1){
                $leave_credits = EmployeeLeaveCredits::where([
                    'employee_id' => $data->employee_id,
                    'enabled' => 1,
                    'leave_type_id' => $data->leave_id
                ])->first();
                
                $remaining_leave = $data->days + $leave_credits->remaining;
                $remaining_hours = $leave_credits->remaining + ($remaining_leave * 8);
                
                

                try {
    
                    DB::connection()->beginTransaction();
    
                    $leave_credits->remaining = $remaining_leave;
                    $leave_credits->hours = $remaining_hours;

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

        DB::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())->save();
            
            $data->touch();

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

            $this->sendNotification($employee_id_for_notification, $data);

            if($request->status == 2){
                try{
                    $ledger = $data;

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

            DB::commit();

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

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


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

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

        if($data->recommending_id != $request->officer_id && $data->approver_id != $request->officer_id){
            return response()->json(['messages' => 'You are not the recommending or approving officer of this record.'], 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);

            Notification::send($email_to, new Overtime($data));

            return response()->json([
                'message' => 'Record Successfully updated!',
                'status' => 'success',
            ],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 approve_undertime_request(Request $request)
    {
        // $data = EmployeeUndertime::with(['employee'])->where('id', $id)->first();
        $data = EmployeeUndertime::with(['employee'])->where('id', $request->id)->first();

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

        if($data->recommending_id != $request->officer_id && $data->approver_id != $request->officer_id){
            return response()->json(['messages' => 'You are not the recommending or approving officer of this record.'], 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 Undertime($data));
                } else {

                    try {
                        $error = [
                            'user_id' => $request->employee_id,
                            'model' => 'App\Model\EmployeeUndertime',
                            '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' => $request->employee_id,
                        'model' => 'App\Model\EmployeeUndertime',
                        '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',
            ],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 approve_travel_request(Request $request)
    {
        // $data = EmployeeOb::with(['employee'])->where('id', $id)->first();
        $data = EmployeeOb::with(['employee'])->where('id', $request->id)->first();

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

        if($data->recommending_id != $request->officer_id && $data->approver_id != $request->officer_id){
            return response()->json(['messages' => 'You are not the recommending or approving officer of this record.'], 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 = '';

            if($request->status == 1){
                $employee_id_for_notification = $data->approver_id;
            } else if ($request->status == 2){
                $employee_id_for_notification = $data->employee_id;
            } else if ($request->status == 99){
                $employee_id_for_notification = $data->employee_id;
            }

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

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

                    try {
                        $error = [
                            'user_id' => $request->employee_id,
                            'model' => 'App\Model\EmployeeOb',
                            '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' => $request->employee_id,
                        'model' => 'App\Model\EmployeeOb',
                        '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',
            ],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 approve_offset_availment_request(Request $request)
    {
        $data = EmployeeOffset::with(['employee'])->where('id', $request->id)->first();

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

        if($data->recommending_id != $request->officer_id && $data->approver_id != $request->officer_id){
            return response()->json(['messages' => 'You are not the recommending or approving officer of this record.'], 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 : '';

            if($request->status == 99){
                $offset = OffsetRemaining::where('employee_id', '=', $data->employee_id)->first();

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

            $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 OffsetAvailment($data));
                } else {

                    try {
                        $error = [
                            'user_id' => $request->employee_id,
                            'model' => 'App\Model\EmployeeOffset',
                            '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' => $request->employee_id,
                        'model' => 'App\Model\EmployeeOffset',
                        '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',
            ],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 approve_offset_earning_request(Request $request)
    {
        $data = EmployeeOffsetEarning::with(['employee'])->where('id', $request->id)->first();

        if (!$data) {
            return response()->json(['messages' => 'No data found.'], 404);
        }
        
        if($data->recommending_id != $request->officer_id && $data->approver_id != $request->officer_id){
            return response()->json(['messages' => 'You are not the recommending or approving officer of this record.'], 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 : '';

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

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

            $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 OffsetEarning($data));
                } else {

                    try {
                        $error = [
                            'user_id' => $request->employee_id,
                            'model' => 'App\Model\EmployeeOffsetEarning',
                            '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' => $request->employee_id,
                        'model' => 'App\Model\EmployeeOffsetEarning',
                        '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',
            ],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 approve_time_adjustment_request(Request $request)
    {
        // $data = EmployeeOb::with(['employee'])->where('id', $id)->first();
        $data = EmployeeTimeAdjustment::with(['employee'])->where('id', $request->id)->first();

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

        if($data->recommending_id != $request->officer_id && $data->approver_id != $request->officer_id){
            return response()->json(['messages' => 'You are not the recommending or approving officer of this record.'], 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 = '';

            if($request->status == 1){
                $employee_id_for_notification = $data->approver_id;
            } else if ($request->status == 2){
                $employee_id_for_notification = $data->employee_id;
            } else if ($request->status == 99){
                $employee_id_for_notification = $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' => $request->employee_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' => $request->employee_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',
            ],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 sendNotification($employee_id, $data)
    {
        $email_to = $this->getEmployeeEmailData($employee_id);

        if ($email_to) {
            Notification::send($email_to, new Leave($data));
        } else {
            return response()->json_encode('Email To Not Found');
        }
    }

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