<?php

namespace App\Http\Controllers;

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\Employee;
use App\Models\EmployeeLeave;
use App\Models\User;
use App\Notifications\Leave;
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 EmployeeLeaveController 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 = EmployeeLeave::with([
            'leave_type',
            'recommending',
            'approving',
            ])->where(function ($query) use ($keyword) {
            $keyword = str_replace(" ", "%", $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);

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

    public function getApprover()
    {
        $employee = Auth::user();
        // dd($employee);

        $result = [];
        $approvers = '';

        if($employee->employees->classification_id == 1){
            $approver_result = $this->getRankAndFileApprover($employee->employees->employee_id);
        } else if ($employee->employees->classification_id == 2) {
            $approver_result = $this->getSupervisorApprover($employee->employees->employee_id);
        }

        return $approver_result;
    }

    public function getRankAndFileApprover($employee_id)
    {
        // get all approver to array then remove the duplicate
        $approvers = [];

        $data = Employee::with('unitApprover')
            ->where('employee_id', $employee_id)
            ->first();

        $approvers[] = $data->unitApprover ? $data->unitApprover->approvers : '';

        $data = Employee::with('sectionApprover')
            ->where('employee_id', $employee_id)
            ->first();
        
        $approvers[] = $data->sectionApprover ? $data->sectionApprover->approvers : '';

        $data = Employee::with('departmentApprover')
        ->where('employee_id', $employee_id)
        ->first();
                                                                                                                                                                     
        $approvers[] = $data->departmentApprover? $data->departmentApprover->approvers : '';

        $data = Employee::with('divisionApprover')
        ->where('employee_id', $employee_id)
        ->first();

        $approvers[] = $data->divisionApprover ? $data->divisionApprover->approvers : '';

        $data = Employee::with('groupDivisionApprover')
        ->where('employee_id', $employee_id)
        ->first();

        $approvers[] = $data->groupDivisionApprover ? $data->groupDivisionApprover->approvers : '';

        $data = Employee::with('dealershipApprover')
        ->where('employee_id', $employee_id)
        ->first();

        $approvers[] = $data->dealershipApprover ? $data->dealershipApprover->approvers : '';

        return $result = [
            'endorser' => $approvers
        ];
    }

    public function getSupervisorApprover($employee_id)
    {
        // get all approver to array then remove the duplicate
        $approvers = [];

        $data = Employee::with('departmentApprover')
        ->where('employee_id', $employee_id)
        ->first();

        $approvers[] = $data->departmentApprover ? $data->departmentApprover->approvers : '';

        $data = Employee::with('divisionApprover')
        ->where('employee_id', $employee_id)
        ->first();

        $approvers[] = $data->divisionApprover ? $data->divisionApprover->approvers : '';

        $data = Employee::with('groupDivisionApprover')
        ->where('employee_id', $employee_id)
        ->first();

        $approvers[] = $data->groupDivisionApprover ? $data->groupDivisionApprover->approvers : '';

        $data = Employee::with('dealershipApprover')
        ->where('employee_id', $employee_id)
        ->first();

        $approvers[] = $data->dealershipApprover ? $data->dealershipApprover->approvers : '';

        return $result = [
            'endorser' => $approvers
        ];
    }

    public function store(Request $request)
    {
        $user = Auth::user();

        $validator = Validator::make($request->all(), [
            'leave_id' => 'required',
            'half_day' => 'required',
            'date_from' => 'required|date',
            'date_to' => 'required|date',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => false,
                'message' => $validator->errors()->first(),
                'errors' => $validator->errors()
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        DB::beginTransaction();
        
        try {
            $attachmentName = $this->handleAttachment($request);

            $status = EmployeeLeave::create([
                'leave_id' => $request->leave_id,
                'employee_id' => $user->employee_id,
                'company_id' => $user->employees->company_id,
                'half_day' => $request->half_day,
                'date_from' => $request->date_from,
                'date_to' => $request->date_to,
                'days' => $request->days,
                'description' => $request->description,
                'attachment' => $attachmentName,
                'recommending_id' => $request->recommending_id,
                'approver_id' => $request->approver_id,
                'status' => 0,
            ]);

            DB::commit();

            $status->load(['employee', 'leave_type']);
            $emailTo = $this->getEmployeeEmailData($request->recommending_id);

            Notification::send($emailTo, new Leave($status));

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

        } 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);
        }
    }

    private function handleAttachment(Request $request)
    {
        if ($request->hasFile('attachment')) {
            $image = $request->file('attachment');
            $attachmentName = time() . '_' . $image->getClientOriginalName();
            $path = "employee-leave/" . $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 = EmployeeLeave::where('id', $id)->first();

        $user = Auth::user();
        
        $validator = Validator::make($request->all(), [
            'leave_id' => "required",
            'half_day' => "required",
            'date_from' => "required|date",
            'date_to' => "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-leave/' . $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-leave/".$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 {
            $data->leave_id = $request->leave_id;
            $data->employee_id = $user->employee_id;
            $data->half_day = $request->half_day;
            $data->date_from = $request->date_from;
            $data->date_to = $request->date_to;
            $data->days = $request->days;
            $data->description = $request->description;
            $data->recommending_id = $request->recommending_id;
            $data->approver_id = $request->approver_id;
            $data->attachment = $attachment_name;
            $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 = EmployeeLeave::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 getEmployeeEmailData($id){
        return User::where('employee_id', '=', $id)->first();
    }
}
