<?php

namespace App\Http\Controllers\Dealers;

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\Models\Dealers\DealerOperation;
use App\Services\DataTableActionLinksService;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\Routing\Controllers\HasMiddleware;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class OperationController extends Controller implements HasMiddleware
{
    /**
     * Define middleware for this controller.
     */
    public static function middleware(): array
    {
        return [
            new Middleware('permission:dealers.operation.view', only: ['index', 'dataTable', 'show']),
            new Middleware('permission:dealers.operation.add', only: ['create', 'store']),
            new Middleware('permission:dealers.operation.delete', only: ['destroy']),
        ];
    }

    /**
     * Display a listing of branches.
     */
    public function index(): View
    {
        return view('operations.index');
    }

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

        return view('operations.modals.form');
    }

    /**
     * Store a newly created branch.
     */
    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'operation' => 'required|string|max:255',

        ]);

        try {
            DB::beginTransaction();

            DealerOperation::create([
                'dealer_id'   => auth()->user()->model_id,
                'operation' => $request->input('operation'),
            ]);

            DB::commit();

            return $this->jsonResponseResponse('Operation created successfully.');
        } catch (\Exception $exception) {
            DB::rollBack();
            Log::error($exception->getMessage(), $exception->getTrace());
            return $this->jsonResponseInternalServerError($exception);
        }
    }

    /**
     * Display a specific branch.
     */
    public function show(string $id): View|JsonResponse
    {
        try {
            $operation = DealerOperation::whereUuid($id)->first();

            if (empty($operation)) {
                throw new NotFoundHttpException('Operation not found.');
            }

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

    /**
     * Show the form for editing a branch.
     */
    public function edit(string $id): View|JsonResponse
    {
        try {
            $operation = DealerOperation::whereUuid($id)->first();

            if (empty($operation)) {
                throw new NotFoundHttpException('Operation not found.');
            }

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

    /**
     * Update the specified branch.
     */
    public function update(Request $request, string $id): JsonResponse
    {
        $request->validate([
            'operation' => 'required|string|max:255',
        ]);

        try {
            $operation = DealerOperation::whereUuid($id)->first();

            if (empty($operation)) {
                throw new NotFoundHttpException('Operation not found.');
            }

            DB::beginTransaction();

            $operation->update([
                'operation' => $request->input('operation'),
            ]);

            DB::commit();

            return $this->jsonResponse('Operation updated successfully.');
        } catch (\Exception $exception) {
            DB::rollBack();
            Log::error($exception->getMessage(), $exception->getTrace());
            return $this->jsonResponseInternalServerError($exception);
        }
    }

    /**
     * Remove the specified branch.
     */
    public function destroy(string $id): JsonResponse
    {
        try {
            $operation = DealerOperation::whereUuid($id)->first();

            if (empty($operation)) {
                throw new NotFoundHttpException('Operation not found.');
            }

            $operation->delete();

            return $this->jsonResponse('Operation deleted successfully.');
        } catch (\Exception $exception) {
            return $this->jsonResponseInternalServerError($exception->getMessage(), $exception->getCode());
        }
    }

    /**
     * DataTable endpoint for branches.
     */
    public function dataTable(Request $request): JsonResponse
    {
        $model = DealerOperation::where('dealer_id', auth()->user()->model_id)->latest();


        $dt = DataTables::of($model);

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

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

            $query->where(function ($q) use ($keywords) {
                foreach ($keywords as $word) {
                    $q->where('operation', 'like', "%$word%");

                }
            });
        });

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

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

        $dt->addColumn('updated', function ($record) {
            return updatedAt($record);
        });

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

            return (new DataTableActionLinksService(
                model: $record,
                routeNamespace: 'operations',
                permissionNamespace: 'dealers.operation',
                datatableId: '#operations-dt',
            ))->byArray($links);
        });

        $dt->addIndexColumn();

        $dt->rawColumns(['operation','created', 'updated', 'actions']);

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