<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Response;

use App\Models\SystemSetting;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Throwable;

class SystemSettingController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {

        $data = SystemSetting::get();

        return response()->json($data, 200);

    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'value' => '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 {

            $data = SystemSetting::create($request->all());

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

    /**
     * Display the specified resource.
     */
    public function show(string $employee_id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        $data = SystemSetting::where('id',$id)->first();

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

        $validator = Validator::make($request->all(), [
                'division_id' => [
                    'required',
                ],
                'name' => [
                    'required',
                    'min:2',
                    Rule::unique('departments')->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);
        }

        DB::connection()->beginTransaction();
        try{
            $data->fill($request->all());
            $data->save();
            $data->touch();
            DB::connection()->commit();
            return response()->json([
                'messages' => "Record successfully updated!",
                "status" => "success",
                "data" => $data
            ],201);
        }catch(Throwable $e){
            DB::connection()->rollback();
            return response()->json([
                'messages' => "Unable to process request. Please try again.",
                'status' => false,
                'data' => $data
            ]);
        }

    }
    /**
     * Update the specified resource in storage.
     */
    public function updateSetting(Request $request)
    {

        DB::connection()->beginTransaction();
        try{
            foreach($request->all() as $row) {
                SystemSetting::where('key', $row['key'])->update(['value' => $row['value']]);
            }
            $data = $request->all();

            DB::connection()->commit();
            return response()->json([
                'messages' => "Record successfully updated!",
                "status" => "success",
                "data" => $data
            ],201);
        }catch(Throwable $e){
            DB::connection()->rollback();
            return response()->json([
                'messages' => "Unable to process request. Please try again.",
                'status' => false,
                'data' => $data
            ]);
        }

    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        $data = SystemSetting::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!"],200);
    }
}
