<?php

namespace App\Http\Controllers;

use App\Models\Cctv;
use App\Services\CctvService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;

class CctvController extends Controller
{
    public function __construct(
        private CctvService $cctvService
    ) {}

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

        $query = Cctv::with(['polda', 'polres', 'polsek'])
            ->orderBy('name');

        // 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);
        }

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

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

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

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

    /**
     * Display the specified CCTV
     */
    public function show(Cctv $cctv)
    {
        $cctv->load(['polda', 'polres', 'polsek', 'snapshots']);
        
        return view('cctvs.show', compact('cctv'));
    }

    /**
     * Find nearby CCTV cameras
     */
    public function nearby(Request $request)
    {
        $validated = $request->validate([
            'latitude' => 'required|numeric',
            'longitude' => 'required|numeric',
            'radius' => 'nullable|integer|min:100|max:5000',
        ]);

        $cctvs = $this->cctvService->findNearbyCctvs(
            $validated['latitude'],
            $validated['longitude'],
            $validated['radius'] ?? 500
        );

        return response()->json([
            'success' => true,
            'cctvs' => $cctvs,
        ]);
    }

    /**
     * Capture snapshot from CCTV
     */
    public function snapshot(Request $request, Cctv $cctv)
    {
        $complaintId = $request->input('complaint_id');
        $complaint = $complaintId ? \App\Models\Complaint::find($complaintId) : null;

        $snapshot = $this->cctvService->captureSnapshot($cctv, $complaint);

        if (!$snapshot) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to capture snapshot',
            ], 500);
        }

        return response()->json([
            'success' => true,
            'snapshot' => $snapshot,
        ]);
    }

    /**
     * Get live stream URL
     */
    public function stream(Cctv $cctv)
    {
        $streamUrl = $this->cctvService->getLiveStreamUrl($cctv);

        return response()->json([
            'success' => true,
            'stream_url' => $streamUrl,
        ]);
    }
}
