<?php

namespace App\Http\Controllers;

use App\Models\Camera;
use Illuminate\Http\Request;

class CameraController extends Controller
{
    public function index()
    {
        $cameras = Camera::orderBy('name')->get();
        return view('cameras.index', compact('cameras'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name'         => 'required|string|max:100',
            'location'     => 'nullable|string|max:200',
            'rtsp_url'     => 'required|string|max:500',
            'snapshot_url' => 'nullable|url|max:500',
            'username'     => 'nullable|string|max:100',
            'password'     => 'nullable|string|max:100',
            'chainage'     => 'nullable|string|max:20',
            'highway'      => 'nullable|string|max:100',
            'latitude'     => 'nullable|numeric|between:-90,90',
            'longitude'    => 'nullable|numeric|between:-180,180',
            'notes'        => 'nullable|string',
            'is_active'    => 'boolean',
        ]);
        $data['is_active'] = $request->boolean('is_active', true);

        Camera::create($data);
        return back()->with('success', "Camera \"{$data['name']}\" added.");
    }

    public function update(Request $request, Camera $camera)
    {
        $data = $request->validate([
            'name'         => 'required|string|max:100',
            'location'     => 'nullable|string|max:200',
            'rtsp_url'     => 'required|string|max:500',
            'snapshot_url' => 'nullable|url|max:500',
            'username'     => 'nullable|string|max:100',
            'password'     => 'nullable|string|max:100',
            'chainage'     => 'nullable|string|max:20',
            'highway'      => 'nullable|string|max:100',
            'latitude'     => 'nullable|numeric|between:-90,90',
            'longitude'    => 'nullable|numeric|between:-180,180',
            'notes'        => 'nullable|string',
        ]);
        $data['is_active'] = $request->boolean('is_active', false);

        $camera->update($data);
        return back()->with('success', "Camera \"{$camera->name}\" updated.");
    }

    public function destroy(Camera $camera)
    {
        $name = $camera->name;
        $camera->delete();
        return back()->with('success', "Camera \"{$name}\" deleted.");
    }

    /** Proxy a JPEG snapshot from the camera's snapshot_url (avoids CORS issues) */
    public function snapshot(Camera $camera)
    {
        if (!$camera->snapshot_url) {
            abort(404, 'No snapshot URL configured.');
        }

        $ctx = stream_context_create(['http' => [
            'timeout'       => 5,
            'ignore_errors' => true,
        ]]);

        $url = $camera->snapshot_url;
        // Inject credentials if username/password set
        if ($camera->username && $camera->password) {
            $url = preg_replace('#(https?://)#', '$1' . rawurlencode($camera->username) . ':' . rawurlencode($camera->password) . '@', $url, 1);
        }

        $data = @file_get_contents($url, false, $ctx);
        if ($data === false) {
            abort(502, 'Could not fetch snapshot from camera.');
        }

        $ct = 'image/jpeg';
        if (isset($http_response_header)) {
            foreach ($http_response_header as $h) {
                if (stripos($h, 'Content-Type:') === 0) {
                    $ct = trim(substr($h, 13));
                    break;
                }
            }
        }

        return response($data, 200, ['Content-Type' => $ct, 'Cache-Control' => 'no-store']);
    }
}
