<?php

namespace App\Http\Controllers;

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\ResignationLetter;
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\Storage;
use Illuminate\Validation\Rule;
use PHPUnit\Event\Code\Throwable;
use Illuminate\Support\Str;

class ResignationLetterController extends Controller
{
    
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        //
        $keyword = $request->input('keyword', '');
        $perPage = $request->input('per_page',PHP_INT_MAX);
        $sortBy = $request->input('sortBy', '');
        $sortType = $request->input('sortType', '');
        $data = ResignationLetter::with('employee:employee_id,firstname,lastname')->where(function ($query) use ($keyword) {
            $keyword = str_replace(" ", "%", $keyword);
            $query->where('employee_id', 'like', '%' . $keyword . '%');
            $query->where('resignation_date', 'like', '%' . $keyword . '%');
        });

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

        $data = $data->paginate($perPage);
        return response()->json($data);
    }

    public function store(Request $request)
    {
        
        // dd($request->all());
        

        $validator = Validator::make($request->all(), [
            'employee_id' => "required",
            'resignation_date' => "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::beginTransaction();
    
            try {
                $attachmentName = $this->handleAttachment($request);

                if (ResignationLetter::where('employee_id', $request->employee_id)->exists()) {
                    ResignationLetter::where('employee_id', $request->employee_id)->update(['enabled' => 0]);
                }

                $Status = ResignationLetter::create([
                    'employee_id' => $request->employee_id,
                    'resignation_date' => $request->resignation_date,
                    'reason' => $request->reason,
                    'attachment' => $attachmentName,
                ]);

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

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

    private function handleAttachment(Request $request)
    {
        if ($request->hasFile('attachment')) {
            $image      = $request->file('attachment');
            $attachmentName  = time().'_'.$image->getClientOriginalName();
            $path       = "resignation-letter/".$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 = ResignationLetter::where('id', $id)->first();
        
        $validator = Validator::make($request->all(), [
            'employee_id' => "required",
            'resignation_date' => "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 = 'resignation-letter/' . $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       = "resignation-letter/".$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->employee_id = $request->employee_id;
            $data->resignation_date = $request->resignation_date;
            $data->reason = $request->reason;
            $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 = ResignationLetter::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);
    }
}
