<?php

namespace App\Http\Controllers\Admin;

use App\Models\User;
use App\Models\Invoice;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Yajra\DataTables\DataTables;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    public function index(Request $request)
    {

        if ($request->ajax()) {

            $data = User::query();

            return Datatables::of($data)
                ->addIndexColumn()
                ->editColumn('created_at', function ($row) {
                    return $row->created_at->format('d-m-Y H:i:s');
                })
                ->addColumn('action', function ($row) {
                    $btn = '<a href="javascript:void(0)" data-toggle="tooltip"  data-id="' . $row->id . '" data-original-title="Edit" class="btn btn-primary btn-xs editData"><i class="fa fa-edit"></i></a>';
                    $btn = $btn . ' <a href="javascript:void(0)" data-toggle="tooltip"  data-id="' . $row->id . '" data-original-title="Delete" class="btn btn-danger btn-xs deleteData"><i class="fa fa-trash"></i></a>';
                    return $btn;
                })
                ->rawColumns(['action'])
                ->make(true);
        }

        return view('admin.user');
    }

    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'name' => 'required',
            'phone' => 'required',
            'role' => 'required',
        ]);

        $user = User::find($request->id);
        User::updateOrCreate(
            [
                'id' => $request->id
            ],
            [
                'name' => $request->name,
                'phone' => $request->phone,
                'amount' => str_replace(',', '', $request->amount),
                'role' => $request->role,
            ]
        );
        if ($user->amount != str_replace(',', '', $request->amount)) {
            $new_balance = $request->amount;
            Invoice::create([
                'user_id' => $request->id,
                'uuid' => (string) Str::uuid(),
                'price' => str_replace(',', '', $request->amount),
                'initial_balance' => str_replace(',', '', $user->amount),
                'new_balance' => str_replace(',', '', $new_balance),
            ]);
        }
        $code = 200;
        $message = 'OK';
        return response()->json([
            'response' => null,
            'metadata' => [
                'code' => $code,
                'message' => $message
            ]
        ], $code);
    }

    public function show($id): JsonResponse
    {
        $data = User::find($id);

        $code = 200;
        $message = 'OK';
        return response()->json([
            'response' => $data,
            'metadata' => [
                'code' => $code,
                'message' => $message
            ]
        ], $code);
    }

    public function destroy(Request $request): JsonResponse
    {
        $request->validate([
            'id' => 'required|integer|exists:users,id',
        ]);
        $updated = User::find($request->id)?->delete();
        return response()->json([
            'response' => null,
            'metadata' => [
                'code' => $updated ? 200 : 404,
                'message' => $updated ? 'OK' : 'Record not found or already inactive',
            ]
        ], $updated ? 200 : 404);
    }

    public function select2(Request $request)
    {
        $query = $request->get('q');
        $limit = 10;

        $data = User::where('email', 'LIKE', "%$query%")
            ->paginate($limit);

        $results = $data->map(function ($item) {
            return [
                'id' => $item->id,
                'text' => $item->email,
            ];
        });

        return response()->json([
            'data' => $results,
            'next_page_url' => $data->nextPageUrl(),
        ]);
    }
}
