<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\DetectionLogModel;
use App\Models\UserModel;
use Illuminate\Support\Facades\Validator;

class DetectionLogController extends Controller
{
    /**
     * Display a listing of the logs with optional search and pagination.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $query = DetectionLogModel::query()->with(['user', 'camera']);

        // Optional search filter
        if ($request->has('search') && !empty($request->search)) {
            $query->whereHas('user', function ($q) use ($request) {
                $q->where('name', 'like', '%' . $request->search . '%');
            })->orWhereHas('camera', function ($q) use ($request) {
                $q->where('camera_name', 'like', '%' . $request->search . '%');
            });
        }

        // Pagination
        $perPage = intval($request->input('itemsPerPage', 10));
        $logs = $query->orderBy('datetime', 'desc')->paginate($perPage);

        return response()->json([
            'data' => $logs->items(),
            'current_page' => $logs->currentPage(),
            'last_page' => $logs->lastPage(),
            'total' => $logs->total(),
            'per_page' => $logs->perPage(),
        ]);
    }

    /**
     * Store a newly created detection log in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'name' => 'required|string',
            'camera_id' => 'required|integer',
        ]);

        // Cek atau buat user berdasarkan nama
        $user = UserModel::firstOrCreate(
            ['name' => $validatedData['name']],
            ['email' => $validatedData['name'] . '@example.com']
        );

        // Simpan log deteksi
        $log = DetectionLogModel::create([
            'user_id' => $user->id,
            'camera_id' => $validatedData['camera_id'],
            'datetime' => now(),
        ]);

        return response()->json($log, 201);
    }


    /**
     * Display the specified log.
     *
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id)
    {
        $log = DetectionLogModel::with(['user', 'camera'])->find($id);

        if (!$log) {
            return response()->json(['message' => 'Detection log not found'], 404);
        }

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

    /**
     * Update the specified log in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'user_id' => 'nullable|exists:tbl_user,id',
            'camera_id' => 'sometimes|required|exists:tbl_cctv,id',
            'datetime' => 'sometimes|required|date',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $log = DetectionLogModel::find($id);

        if (!$log) {
            return response()->json(['message' => 'Detection log not found'], 404);
        }

        $log->update($validator->validated());
        return response()->json($log);
    }

    /**
     * Remove the specified log from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        $log = DetectionLogModel::find($id);

        if (!$log) {
            return response()->json(['message' => 'Detection log not found'], 404);
        }

        $log->delete();
        return response()->json(['message' => 'Detection log deleted successfully']);
    }
}