<?php

namespace App\Http\Controllers;

use App\Models\FieldReport;
use App\Models\Dispatch;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class FieldReportController extends Controller
{
    /**
     * Display a listing of field reports
     */
    public function index(Request $request)
    {
        $query = FieldReport::with(['dispatch.complaint', 'officer.user'])
            ->orderBy('created_at', 'desc');

        // Filter based on user role
        $user = $request->user();
        if ($user->role === 'petugas' && $user->officer) {
            $query->where('officer_id', $user->officer->id);
        }

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

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

        return view('field-reports.index', compact('fieldReports'));
    }

    /**
     * Store a newly created field report
     */
    public function store(Request $request, Dispatch $dispatch)
    {
        $validated = $request->validate([
            'description' => 'required|string',
            'photos' => 'nullable|array',
            'photos.*' => 'image|max:5120',
            'videos' => 'nullable|array',
            'videos.*' => 'mimes:mp4,avi,mov|max:10240',
            'latitude' => 'nullable|numeric',
            'longitude' => 'nullable|numeric',
        ]);

        $user = $request->user();
        $officer = $user->officer;

        if (!$officer) {
            return response()->json(['error' => 'User is not an officer'], 403);
        }

        // Upload photos
        $photoPaths = [];
        if ($request->hasFile('photos')) {
            foreach ($request->file('photos') as $photo) {
                $photoPaths[] = $photo->store('field-reports/photos', 'public');
            }
        }

        // Upload videos
        $videoPaths = [];
        if ($request->hasFile('videos')) {
            foreach ($request->file('videos') as $video) {
                $videoPaths[] = $video->store('field-reports/videos', 'public');
            }
        }

        $fieldReport = FieldReport::create([
            'dispatch_id' => $dispatch->id,
            'officer_id' => $officer->id,
            'status' => 'completed',
            'description' => $validated['description'],
            'photos' => $photoPaths,
            'videos' => $videoPaths,
            'latitude' => $validated['latitude'] ?? null,
            'longitude' => $validated['longitude'] ?? null,
            'completed_at' => now(),
        ]);

        return response()->json([
            'success' => true,
            'field_report' => $fieldReport->load(['dispatch', 'officer']),
        ], 201);
    }

    /**
     * Display the specified field report
     */
    public function show(FieldReport $fieldReport)
    {
        $fieldReport->load(['dispatch.complaint', 'officer.user']);
        
        return view('field-reports.show', compact('fieldReport'));
    }
}
