<?php

namespace App\Http\Controllers;

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\EmployeeOvertime;
use App\Models\User;
use App\Notifications\Overtime;
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 EmployeeOvertimeController extends Controller
{
    
    /**
     * Display a listing of the resource.
     */
    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 = EmployeeOvertime::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',
                'date_to',
                'from_time',
                'to_time',
                'hours', 
                'break_time',
                'charge_to', 
                'attachment', 
                'description', 
                'denied_reason', 
                'meal', 
                'meal_amount',
                'transportation', 
                'transportation_amount',
                'status', 
                'validated_at',
                'validated_by',
                'validated',
                'deferred_reason',
                'recommending_id', 
                'allow_higher_approval',
                'approver_id', 
                'recommended_at',
                'approved_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 ($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('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);
                    });
                }
            });
        }   

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

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

        $month = date('m');
        $year = date('Y');

        $totalOTForThisMonth = EmployeeOvertime::select(DB::raw("SUM(hours) as total_hours"))
            ->where(function($query) use ($month, $year) {
                $query->where(function($q) use ($month, $year) {
                    $q->whereMonth('date_from', $month)
                    ->whereYear('date_from', $year);
                })->orWhere(function($q) use ($month, $year) {
                    $q->whereMonth('date_to', $month)
                    ->whereYear('date_to', $year);
                });
            })
            ->where('enabled', 1)
            ->where('status', 2)
            ->where('employee_id', $employee->employee_id)
            ->first();

        $totalOTForThisYear = EmployeeOvertime::select(DB::raw("SUM(hours) as total_hours"))
            ->where(function($query) use ($year) {
                $query->whereYear('date_from', $year)
                    ->orWhereYear('date_to', $year);
            })
            ->where('enabled', 1)
            ->where('status', 2)
            ->where('employee_id', $employee->employee_id)
            ->first();

        $averageOTForThisMonth = EmployeeOvertime::select(DB::raw("SUM(hours) as total_hours"))
            ->where(function($query) use ($month, $year) {
                $query->where(function($q) use ($month, $year) {
                    $q->whereMonth('date_from', $month)
                    ->whereYear('date_from', $year);
                })->orWhere(function($q) use ($month, $year) {
                    $q->whereMonth('date_to', $month)
                    ->whereYear('date_to', $year);
                });
            })
            ->where('enabled', 1)
            ->where('status', 2)
            ->where('employee_id', $employee->employee_id)
            ->avg('hours') ?? 0; // Return 0 if no records found
            
        return response()->json([
            'data' => $data,
            'total_ot_for_the_month' => $totalOTForThisMonth,
            'total_ot_for_the_year' => $totalOTForThisYear,
            'avg_ot_for_the_month' => number_format($averageOTForThisMonth, 1),
        ]);
    }

    public function getOvertimeList(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);

        $payrollSettings = \App\Models\PayrollSetting::select('overtime_meal_amount','overtime_meal_every_hours')->first();
        // dd($payrollSettings->overtime_meal_amount);
        $data = EmployeeOvertime::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',
                'date_to',
                'from_time',
                'to_time',
                'hours', 
                'break_time',
                'charge_to', 
                'attachment', 
                'description', 
                'denied_reason', 
                'meal', 
                'meal_amount',
                'transportation',
                'transportation_amount', 
                'status', 
                'validated_at',
                'validated_by',
                'validated',
                'deferred_reason',
                'recommending_id', 
                'allow_higher_approval',
                'approver_id', 
                'recommended_at',
                'approved_at',
                'created_at',
                'posted'
            )
            ->where('status',2)
            ->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_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('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->orderBy('validated', 'asc')->paginate(500);
        
        return response()->json([
            'data' => $data,
            'PayrollSettings' => $payrollSettings
        ]);
    }

    public function store(Request $request)
    {
        // dd($request->all());
        $user = Auth::user();
        
        $validator = Validator::make($request->all(), [
            'date_from' => "required|date",
            'date_to' => "required|date",
            'from_time' => "required",
            'to_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 {
            $transpo = ($request->transportation && $request->transportation !== 'null' && $request->transportation !== 'false' && trim($request->transportation) !== '' ? 1 : 0);
            $meal = ($request->meal && $request->meal !== 'null' && $request->meal !== 'false' && trim($request->meal) !== '' ? 1 : 0);

            $meal_amount = ($request->meal && $request->meal !== 'null' && $request->meal !== 'false' && trim($request->meal) !== '' ? 60 : 0);

            $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 = EmployeeOvertime::create([
                'employee_id' => $user->employee_id,
                'company_id' => $user->employees->company_id,
                'dealer_id' => $user->employees->dealer_id,
                'date_from' => $request->date_from,
                'date_to' => $request->date_to,
                'from_time' => $request->from_time,
                'to_time' => $request->to_time,
                'hours' => $request->hours,
                'charge_to' => $request->charge_to,
                'break_time' => $request->break_time,
                'allow_higher_approval' => $allow_higher_approval,
                'meal' => $meal,
                'transportation' => $transpo,
                'meal_amount' => $meal_amount,
                'description' => $request->description,
                'attachment' => $attachmentName,
                'recommending_id' => $request->recommending_id[0],
                'approver_id' => $request->approver_id[0] ?? $request->recommending_id[0],
                'status' => 0,
            ]);

            // dd($Status);

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

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

            $email_to = $this->getEmployeeEmailData($request->recommending_id[0]);

            try{
                if($email_to != ''){
                    Notification::send($email_to, new Overtime($Status));
                }
            } catch (Exception $e) {
                // Log the error or handle it as needed
                // For this example, we'll just ignore email sending failures
            }

            return response()->json([
                'status'  => true,
                'message' => 'Saved successfully!',
                'data'    => $Status
            ],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 handleAttachment(Request $request)
    {
        if ($request->hasFile('attachment')) {
            $image = $request->file('attachment');
            $attachmentName = time() . '_' . $image->getClientOriginalName();
            $path = "employee-overtime/" . $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)
    {
        $id = $request->id;

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

        $user = Auth::user();
        
        $validator = Validator::make($request->all(), [
            'date_from' => "required|date",
            'date_to' => "required|date",
            'from_time' => "required",
            'to_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);
        }

        $attachment_name = $request->attachment;

        if($data->attachment != $request->attachment)
        {
            $attachment_file_path = 'employee-overtime/' . $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-overtime/".$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 {
            $transpo = ($request->transportation && $request->transportation !== 'null' && $request->transportation !== 'false' && trim($request->transportation) !== '' ? 1 : 0);
            $meal = ($request->meal && $request->meal !== 'null' && $request->meal !== 'false' && trim($request->meal) !== '' ? 1 : 0);

            $meal_amount = ($request->meal && $request->meal !== 'null' && $request->meal !== 'false' && trim($request->meal) !== '' ? 60 : 0);

            $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->date_from = $request->date_from;
            $data->date_to = $request->date_to;
            $data->from_time = $request->from_time;
            $data->to_time = $request->to_time;
            $data->break_time = $request->break_time == 'null' ? NULL : $request->charge_to;
            $data->charge_to = $request->charge_to == 'null' ? NULL : $request->charge_to;
            $data->allow_higher_approval = $allow_higher_approval;
            $data->meal = $meal;
            $data->transportation = $transpo;
            $data->meal_amount = $meal_amount;
            $data->hours = $request->hours;
            $data->description = $request->description;
            $data->attachment = $attachment_name;
            $data->recommending_id = $request->recommending_id[0];
            $data->approver_id = $request->approver_id[0] ?? $request->recommending_id[0];
            $data->save();
            
            
            DB::connection()->commit();

            return response()->json([
                'status'  => true,
                'message' => 'Saved successfully!',
                '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 destroy(int $id)
    {
        $data = EmployeeOvertime::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 = EmployeeOvertime::where('id', $id)->first();

        $data->attachment = NULL;

        $data->save();

        DB::connection()->commit();
        
        $attachment_file_path = 'employee-overtime/' . $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();
    }
}
