<?php

namespace App\Http\Controllers;

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\Requirements;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Crypt;
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 RequirementsController 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 = Requirements::where(function ($query) use ($keyword) {
            $keyword = str_replace(" ", "%", $keyword);
            $query->where('description', 'like', '%' . $keyword . '%');
        });

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

        $data = $data->paginate($perPage);
        return response()->json($data);
    }
    
    public function show(string $id)
    {
        try {
            $id = Crypt::decrypt($id);
        } catch (\Illuminate\Contracts\Encryption\DecryptException $e) {
            $id = $id;
        }

        $data = Requirements::with('requirement_list')->where('employee_id', '=',$id)->get();
        
        return response()->json($data);
    }

    public function store(Request $request)
    {
        try {
            $request['employee_id'] = Crypt::decrypt($request->employee_id);
        } catch (\Illuminate\Contracts\Encryption\DecryptException $e) {
            $request['employee_id'] = $request->employee_id;
        }
        
        // Validate the incoming request data
        $validator = Validator::make($request->all(), [
            'description' => [
                'required',
                'min:2',
                Rule::unique('requirements')->whereNull('deleted_at')
            ]
        ]);

        /** 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 {
            $attachmentName = $this->handleAttachment($request);

            $data = Requirements::create([
                "employee_id" => $request->employee_id,
                "description" => $request->description,
                "date_requested" => $request->date_requested,
                "last_submit_date" => $request->last_submit_date,
                "date_submitted" => $request->date_submitted,
                "expiration_date" => $request->expiration_date,
                "remarks" => $request->remarks,
                "requirement_list_id" => $request->requirement_list_id,
                "attachment" => $attachmentName
            ]);

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

            return response()->json([
                'message' => 'Record Successfully added!',
                '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 update(Request $request)
    {
        $id = $request->id;

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

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

        $validator = Validator::make($request->all(),
            [
                'description' => [
                    'required',
                    'min:2',
                    Rule::unique('requirements')->ignore($id)->whereNull('deleted_at')
                ]
            ]
        );

        /** 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 = 'requirements/' . $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       = "requirements/".$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->employee_id = $request->employee_id;
            $data->description = $request->description;
            $data->date_requested = $request->date_requested;
            $data->last_submit_date = $request->last_submit_date;
            $data->date_submitted = $request->date_submitted;
            $data->expiration_date = $request->expiration_date;
            $data->remarks = $request->remarks;
            $data->requirement_list_id = $request->requirement_list_id;
            $data->attachment = $attachment_name;

            $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 destroy(int $id)
    {
        $data = Requirements::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 handleAttachment(Request $request)
    {
        if ($request->hasFile('attachment')) {
            $image = $request->file('attachment');
            $attachmentName = time() . '_' . $image->getClientOriginalName();
            $path = "requirements/" . $attachmentName;
            if (Storage::disk('local')->put($path, file_get_contents($image))) {
                return $attachmentName;
            }
            throw new Exception('Unable to process attachment.');
        }
        return '';
    }
}
