<?php

namespace App\Http\Controllers\DexUsers;

use App\Models\DexUser;
// use App\Models\State;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Yajra\DataTables\DataTables;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use App\Services\DataTableActionLinksService;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\Routing\Controllers\HasMiddleware;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class DexUserController extends Controller implements HasMiddleware
{
    /**
     * Get the middleware for the controller.
     *
     * @return array
     */
    public static function middleware(): array
    {
        return [
            new Middleware('permission:dex-user.view', only: ['index', 'dataTable', 'show']),
            new Middleware('permission:dex-user.add', only: ['create', 'store', 'edit']),
            new Middleware('permission:dex-user.delete', only: ['destroy']),
        ];
    }

    /**
     * Display a listing of the resource.
     */
    public function index(): View
    {
        return view('dex-users.index');
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(): View
    {

        return view('dex-users.modals.form');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'first_name'=> 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email'     => 'required|email|unique:users,email',
        ]);

        try {
            DB::beginTransaction();

            DexUser::create([
                'first_name'     => $request->input('first_name'),
                'last_name'      => $request->input('last_name'),
                'email'          => $request->input('email'),
            ]);

            DB::commit();

            return $this->jsonResponse(['message' => __('dex-user.messages.create_success') ]);
            //  $this->sendSuccessResponse(__('dex-user.messages.create_success'));
        } catch (\Exception $exception) {
            DB::rollBack();
            Log::error($exception->getMessage(), $exception->getTrace());
            return $this->jsonResponseInternalServerError($exception);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $uuid)
    {
        try {
            $dexUser = DexUser::whereUuid($uuid)->firstOrFail();

            return view('dex-users.modals.show', compact('dexUser'));
        } catch (\Exception $exception) {
            return $this->jsonResponseInternalServerError($exception->getMessage(), $exception->getCode());
        }
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $uuid)
    {
        try {
            $dexUser = DexUser::whereUuid($uuid)->firstOrFail();

            return view('dex-users.modals.form', compact('dexUser'));
        } catch (\Exception $exception) {
            return $this->jsonResponseInternalServerError($exception->getMessage(), $exception->getCode());
        }
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $uuid): JsonResponse
    {
        $request->validate([
            'first_name'=> 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email'     => 'required|email|unique:users,email',
        ]);

        try {
            $dexUser = DexUser::whereUuid($uuid)->firstOrFail();

            DB::beginTransaction();

            $dexUser->update([
                'first_name'     => $request->input('first_name'),
                'last_name'      => $request->input('last_name'),
                'email'          => $request->input('email'),
            ]);

            DB::commit();

            return $this->jsonResponse(['message' =>__('dex-user.messages.update_success') ]);
        } catch (\Exception $exception) {
            DB::rollBack();
            Log::error($exception->getMessage(), $exception->getTrace());
            return $this->jsonResponseInternalServerError($exception);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $uuid): JsonResponse
    {
        try {
            $DexUser = DexUser::whereUuid($uuid)->firstOrFail();

            $DexUser->delete();

            return $this->jsonResponse(['message' => __('dex-user.messages.delete_success')]);
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->jsonResponseInternalServerError($exception->getMessage(), $exception->getCode());
        }
    }

    /**
     * Return the listing of the resource for DataTable.
     */
    public function dataTable(Request $request): JsonResponse
    {
        $model = DexUser::latest();
        $dt    = DataTables::of($model);

        $dt->filter(function ($query) use ($request) {
            if (empty($request->input('search'))) {
                return;
            }

            $search   = trim($request->input('search')['value']);
            $keywords = explode(' ', $search);


            foreach ($keywords as $word) {
                $query->where(function ($sq) use ($word) {
                    $sq->where('first_name', 'like', "%$word%")
                        ->orWhere('last_name', 'like', "%$word%")
                        ->orWhere('email', 'like', "%$word%");
                });
            }
        });

        $dt->addColumn('first_name', function ($record) {
            return ucwords($record->first_name);
        });

        $dt->addColumn('last_name', function ($record) {
            return ucwords($record->last_name);
        });

        $dt->addColumn('email', function ($record) {
            return canEmpty($record->email);
        });

        $dt->addColumn('created', function ($record) {
            return humanTime($record->created_at);
        });

        $dt->addColumn('updated', function ($record) {
            return $record->updated_at ? humanTime($record->updated_at) : 'null';
        });

        $dt->addColumn('actions', function ($record) {
            $links = [
                ['action' => 'update', 'modalSize' => 'lg'],
                ['action' => 'view', 'modalSize' => 'lg'],
                ['action' => 'delete'],
            ];

            return (new DataTableActionLinksService(
                model: $record,
                routeNamespace: 'dex-users',
                permissionNamespace: 'dex-user',
                datatableId: '#dex-user-dt',
            ))->byArray($links);
        });

        $dt->addIndexColumn();

        $dt->rawColumns(['uuid', 'first_name', 'last_name', 'email', 'created', 'updated', 'actions']);

        return $dt->make(true);
    }
}
