<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\Apps;
use App\Models\AppsStorage;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Throwable;

class AppController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $perPage = $request->input('per_page',PHP_INT_MAX);

        $keyword = $request->input('keyword', '');

        $data = Apps::with(['modules'])->where(fn($q) =>
            $q->where('name', 'like', '%'.$keyword.'%')

        )
        ->where('enabled',1)
        ->orderBy('name')->paginate($perPage);

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        /** Validate the incoming request data */
        $validator = Validator::make($request->only(['name']), [
            'name' => [
                'required',
                Rule::unique('apps')->whereNull('deleted_at'),
            ],
        ]);

        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 {

            $request_data = array_merge($request->all(), ['created_at'    => $this->current_datetime,
            'updated_at'    => $this->current_datetime]);

            $module = Apps::create($request_data);

            DB::commit();

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

        } catch (Throwable $e) {

            DB::rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ]);
        }
    }

    public function show($id)
    {
        return response()->json([
            'status'  => true,
            'message' => 'App info',
            'data'    => Apps::find($id)
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {

        /** Fetch the record first to check if it exists */
        $data = Apps::find($id);

        /** If not exists return with error message */
        if (!$data) {
            return response()->json(['message' => 'Record not found.'], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        /** Validate the incoming request data */
        $validator = Validator::make(array_merge($request->only(['name']), ['id' => $id]), [
            'name' => [
                'required',
                Rule::unique('apps')->ignore($id)->whereNull('deleted_at'),
            ],
        ]);

        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 {

            // update

            $request_data = array_merge($request->all(), ['updated_at'    => $this->current_datetime]);

            $data->fill($request_data);
            $data->save();

            $data->touch();

            DB::commit();

            return response()->json([
                'status'  => true,
                'message' => 'Updated successfully!',
                'data'    => $data
            ], 201);

        } catch (Throwable $e) {

            DB::rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ]);
        }
    }
    /**
     * Remove the specified resource from storage.
     */
    public function destroy(int $id)
    {
        $data = Apps::find($id);

        if(!$data) {
            return response()->json(['message' => 'Record not found!'],204);
        }

        $data->delete();

        DB::commit();

        return response()->json([
            'message' => 'Record Successfully deleted!',
        ], 200);
    }

    public function saveAppsStorage(Request $request)
    {
        /** Validate the incoming request data */
        $validator = Validator::make($request->all(), [
            'employee_id' => 'required',
            'system_id' => 'required',
            'data' => 'required'
        ]);

        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 {

            // create
            AppsStorage::where([
                'employee_id' => $request->employee_id,
                'system_id' => $request->system_id,
            ])->delete();

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

            DB::commit();

            return response()->json([
                'status'  => true,
                'message' => 'Updated successfully!',
                'data'    => $data
            ], 201);

        } catch (Throwable $e) {

            DB::rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ]);
        }
    }

    public function getAppsStorage(Request $request)
    {
        try {
            // DB::enableQueryLog();
            $data = AppsStorage::where('system_id', $request->system_id)
            ->where('employee_id', $request->employee_id)
            ->first();
            
            // dd(DB::getQueryLog());
            return response()->json($data, 200);

        } catch (Throwable $e) {

            DB::rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ], 422);
        }
    }
}
