<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Incident;
use Illuminate\Support\Facades\Validator;

class IncidentController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $query = Incident::query();

        // Apply filters if provided
        if ($request->filled('region')) {
            $query->byRegion($request->region);
        }

        if ($request->filled('category')) {
            $query->byCategory($request->category);
        }

        if ($request->filled('start_date') && $request->filled('end_date')) {
            $query->byDateRange($request->start_date, $request->end_date);
        }

        $incidents = $query->latest()->paginate(15);

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

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('incidents.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'year' => 'required|integer|min:1900|max:' . date('Y'),
            'month' => 'required|string|max:20',
            'day' => 'required|integer|min:1|max:31',
            'hour' => 'required|string|max:10',
            'region' => 'required|string|max:255',
            'country' => 'required|string|max:255',
            'state' => 'required|string|max:255',
            'local_government' => 'required|string|max:255',
            'city_town' => 'required|string|max:255',
            'village' => 'nullable|string|max:255',
            'sub_division_block' => 'nullable|string|max:255',
            'road_exact_location' => 'nullable|string|max:255',
            'latitude' => 'nullable|numeric|between:-90,90',
            'longitude' => 'nullable|numeric|between:-180,180',
            'incident_category' => 'required|string|max:255',
            'main_victim' => 'nullable|string|max:255',
            'government_involve' => 'boolean',
            'civilian' => 'nullable|string|max:255',
            'military' => 'boolean',
            'nsag' => 'nullable|string|max:255',
            'deaths' => 'required|integer|min:0',
            'injured' => 'required|integer|min:0',
            'affected' => 'required|integer|min:0',
            'perpetrator' => 'nullable|string|max:255',
            'source' => 'required|string|max:255',
            'time_before_attack' => 'nullable|string',
            'action_taken' => 'nullable|string|max:255',
            'by_who' => 'nullable|string|max:255',
            'brief_narrative' => 'required|string',
            'comment' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        // Add user_id explicitly
        $data = $request->except('_token');
        $data['user_id'] = auth()->id();

        Incident::create($data);

        return redirect()->route('incidents.index')
            ->with('success', 'Incident registered successfully.');
    }

    /**
     * Display the specified resource.
     */
    public function show(Incident $incident)
    {
        return view('incidents.show', compact('incident'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Incident $incident)
    {
        return view('incidents.edit', compact('incident'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Incident $incident)
    {
        $validator = Validator::make($request->all(), [
            'year' => 'required|integer|min:1900|max:' . date('Y'),
            'month' => 'required|string|max:20',
            'day' => 'required|integer|min:1|max:31',
            'hour' => 'required|string|max:10',
            'region' => 'required|string|max:255',
            'country' => 'required|string|max:255',
            'state' => 'required|string|max:255',
            'local_government' => 'required|string|max:255',
            'city_town' => 'required|string|max:255',
            'village' => 'nullable|string|max:255',
            'sub_division_block' => 'nullable|string|max:255',
            'road_exact_location' => 'nullable|string|max:255',
            'latitude' => 'nullable|numeric|between:-90,90',
            'longitude' => 'nullable|numeric|between:-180,180',
            'incident_category' => 'required|string|max:255',
            'main_victim' => 'nullable|string|max:255',
            'government_involve' => 'boolean',
            'civilian' => 'nullable|string|max:255',
            'military' => 'boolean',
            'nsag' => 'nullable|string|max:255',
            'deaths' => 'required|integer|min:0',
            'injured' => 'required|integer|min:0',
            'affected' => 'required|integer|min:0',
            'perpetrator' => 'nullable|string|max:255',
            'source' => 'required|string|max:255',
            'time_before_attack' => 'nullable|string',
            'action_taken' => 'nullable|string|max:255',
            'by_who' => 'nullable|string|max:255',
            'brief_narrative' => 'required|string',
            'comment' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $incident->update($request->all());

        return redirect()->route('incidents.index')
            ->with('success', 'Incident updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Incident $incident)
    {
        $incident->delete();

        return redirect()->route('incidents.index')
            ->with('success', 'Incident deleted successfully.');
    }

    /**
     * Export incidents to CSV
     */
    public function export()
    {
        $incidents = Incident::all();
        
        $filename = 'incidents_' . date('Y-m-d_H-i-s') . '.csv';
        
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
        ];

        $callback = function() use ($incidents) {
            $file = fopen('php://output', 'w');
            
            // CSV headers
            fputcsv($file, [
                'ID', 'Year', 'Month', 'Day', 'Hour', 'Region', 'Country', 'State',
                'Local Government', 'City/Town', 'Village', 'Sub Division/Block',
                'Road/Exact Location', 'Latitude', 'Longitude', 'Incident Category',
                'Main Victim', 'Government Involve', 'Civilian', 'Military', 'NSAG',
                'Deaths', 'Injured', 'Affected', 'Perpetrator', 'Source',
                'Time Before Attack', 'Action Taken', 'By Who', 'Brief Narrative',
                'Comment', 'Created At', 'Updated At'
            ]);
            
            // Data rows
            foreach ($incidents as $incident) {
                fputcsv($file, [
                    $incident->id,
                    $incident->year,
                    $incident->month,
                    $incident->day,
                    $incident->hour,
                    $incident->region,
                    $incident->country,
                    $incident->state,
                    $incident->local_government,
                    $incident->city_town,
                    $incident->village,
                    $incident->sub_division_block,
                    $incident->road_exact_location,
                    $incident->latitude,
                    $incident->longitude,
                    $incident->incident_category,
                    $incident->main_victim,
                    $incident->government_involve ? 'Yes' : 'No',
                    $incident->civilian,
                    $incident->military ? 'Yes' : 'No',
                    $incident->nsag,
                    $incident->deaths,
                    $incident->injured,
                    $incident->affected,
                    $incident->perpetrator,
                    $incident->source,
                    $incident->time_before_attack,
                    $incident->action_taken,
                    $incident->by_who,
                    $incident->brief_narrative,
                    $incident->comment,
                    $incident->created_at,
                    $incident->updated_at,
                ]);
            }
            
            fclose($file);
        };

        return response()->stream($callback, 200, $headers);
    }
}