<?php

namespace App\Http\Controllers;

use App\Models\Officer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;

class OfficerController extends Controller
{
    /**
     * Display a listing of officers
     */
    public function index(Request $request)
    {
        if (!Schema::hasTable('officers')) {
            $officers = $this->emptyPaginator();
            return view('officers.index', compact('officers'));
        }

        $query = Officer::with(['user', 'polda', 'polres', 'polsek'])
            ->orderBy('nip');

        // Filter based on user role
        $user = $request->user();
        if ($user && $user->role === 'polda' && $user->polda_id) {
            $query->where('polda_id', $user->polda_id);
        } elseif ($user && $user->role === 'polres' && $user->polres_id) {
            $query->where('polres_id', $user->polres_id);
        } elseif ($user && $user->role === 'polsek' && $user->polsek_id) {
            $query->where('polsek_id', $user->polsek_id);
        }

        if ($request->has('status')) {
            $query->where('status', $request->status);
        }

        if ($request->has('unit_type')) {
            $query->where('unit_type', $request->unit_type);
        }

        $officers = $query->paginate(20);

        return view('officers.index', compact('officers'));
    }

    /**
     * Update officer location
     */
    public function updateLocation(Request $request, Officer $officer)
    {
        $validated = $request->validate([
            'latitude' => 'required|numeric',
            'longitude' => 'required|numeric',
        ]);

        $officer->update([
            'current_latitude' => $validated['latitude'],
            'current_longitude' => $validated['longitude'],
            'last_location_update' => now(),
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Location updated',
        ]);
    }
}
