<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\EmployeeOffsetEarning;
use App\Models\NotificationErrorLog;
use App\Models\OffsetRemaining;
use App\Models\User;
use App\Notifications\OffsetEarning;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Notification;
use Throwable;

class OffsetEarningApprovalController 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 = EmployeeOffsetEarning::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_offset_earnings.*')
            ->selectRaw('
                (SELECT COUNT(*) FROM employee_offset_earnings AS el 
                WHERE el.status IN (0, 1) 
                AND (el.recommending_id = '.$currentEmp.' OR el.approver_id = '.$currentEmp.')
                AND el.deleted_at IS NULL) AS pending,
                (SELECT COUNT(*) FROM employee_offset_earnings AS el 
                WHERE el.status = 2 
                AND (el.recommending_id = '.$currentEmp.' OR el.approver_id = '.$currentEmp.')
                AND el.deleted_at IS NULL) AS approved,
                (SELECT COUNT(*) FROM employee_offset_earnings AS el 
                WHERE el.status = 99 
                AND (el.recommending_id = '.$currentEmp.' OR el.approver_id = '.$currentEmp.')
                AND el.deleted_at IS NULL) AS denied')
            ->orderBy('status', 'ASC')
            ->paginate($perPage);

        // dd($data);
        // dd(DB::getQueryLog());

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

    public function update(Request $request, int $id)
    {
        $data = EmployeeOffsetEarning::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 : '';

            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' => Auth::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' => Auth::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',
                '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 = EmployeeOffsetEarning::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 OffsetEarning($data));
                    } else {

                        try {
                            $error = [
                                'user_id' => Auth::id(),
                                'model' => 'App\Model\EmployeeLeave',
                                '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\EmployeeLeave',
                            '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();
    }
}
