<?php
namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\PlateNumberModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PlateNumberController extends Controller
{
    public function index(Request $request)
    {
        try {
            $itemsPerPage = $request->get('itemsPerPage', 10);
            $search       = $request->get('search', '');

            // Fetch plate numbers with user data using Eloquent
            $plateNumbers = PlateNumberModel::with('user.office')
                ->where('status', 1)
                ->where('plate_number', 'like', "%{$search}%")
                ->orderBy('created_at', 'desc')
                ->paginate($itemsPerPage);

            return response()->json($plateNumbers, 200);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Error fetching plate numbers.', 'error' => $e->getMessage()], 500);
        }
    }

    public function store(Request $request)
    {
        $request->validate([
            'user_id'      => 'required|exists:tbl_user,id',
            'plate_number' => 'required|string|max:20|unique:tbl_plate_number,plate_number',
        ]);

        try {
            PlateNumberModel::create([
                'user_id'      => $request->input('user_id'),
                'plate_number' => $request->input('plate_number'),
                'status'       => 1,
                'created_at'   => now('Asia/Jakarta'),
            ]);

            return response()->json(['message' => 'Plate number added successfully.'], 201);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Error adding plate number.', 'error' => $e->getMessage()], 500);
        }
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'user_id'      => 'required|exists:tbl_user,id',
            'plate_number' => 'required|string|max:20|unique:tbl_plate_number,plate_number,' . $id,
        ]);

        try {
            $plateNumber = PlateNumberModel::findOrFail($id);
            $plateNumber->update([
                'user_id'      => $request->input('user_id'),
                'plate_number' => $request->input('plate_number'),
                'updated_at'   => now('Asia/Jakarta'),
            ]);

            return response()->json(['message' => 'Plate number updated successfully.'], 200);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Error updating plate number.', 'error' => $e->getMessage()], 500);
        }
    }

    public function destroy($id)
    {
        try {
            $plateNumber = PlateNumberModel::findOrFail($id);
            $plateNumber->update([
                'status'     => 0, // Soft delete
                'updated_at' => now('Asia/Jakarta'),
            ]);

            return response()->json(['message' => 'Plate number deactivated successfully.'], 200);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Error deleting plate number.', 'error' => $e->getMessage()], 500);
        }
    }

    public function getUserByPlateNumber(Request $request)
    {
        // Validasi input minimal
        $request->validate([
            'plate_number' => 'required|string|max:20',
        ]);

        // Bersihkan spasi dari input
        $rawPlate   = $request->input('plate_number');
        $cleanPlate = preg_replace('/\s+/', '', $rawPlate);

        // Ambil data user + office + level_name, bandingkan plat tanpa spasi (case-insensitive)
        $row = DB::table('tbl_plate_number as pn')
            ->join('tbl_user as u', 'pn.user_id', '=', 'u.id')
            ->leftJoin('tbl_office as o', 'u.office_id', '=', 'o.id')
            ->leftJoin('tbl_user_level as l', 'u.level_id', '=', 'l.id') // <--- join level
            ->select(
                'pn.id as plate_id',
                'pn.plate_number',
                'pn.status',
                'u.id as user_id',
                'u.username',
                'u.ai_label',
                'u.nama_lengkap',
                'u.email',
                'u.level_id',
                DB::raw('COALESCE(l.level_name, "") as level_name'),
                'u.jabatan',
                'u.nip',
                'o.office_name'
            )
            ->where('pn.status', 1)
            ->whereRaw("UPPER(REPLACE(pn.plate_number, ' ', '')) = UPPER(?)", [$cleanPlate])
            ->first();

        if (! $row) {
            return response()->json([
                'status'  => false,
                'message' => 'PLATE NUMBER NOT FOUND',
                'data'    => null,
            ], 404);
        }

        return response()->json([
            'status'  => true,
            'message' => 'User fetched successfully.',
            'data'    => $row,
        ], 200);
    }

}