<?php
namespace App\Controllers\Admin;

use Core\View;
use App\Models\Incident;

class ReportController
{
    public function index()
    {
        View::make('admin/reports')
            ->setLayout('admin_layout')
            ->with(['title' => 'Generate Reports'])
            ->render();
    }

    public function generateCSV()
    {
        // Use output buffering to generate a raw CSV file download
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="ercs_incident_report_' . date('Y-m-d') . '.csv"');
        
        $output = fopen('php://output', 'w');
        
        // Write CSV Headers
        fputcsv($output, ['Incident ID', 'Date Reported', 'Victim Name', 'Category', 'Status', 'Assigned Responder ID', 'GPS Coordinates']);
        
        $sql = "
            SELECT i.*, c.name as category_name, v.full_name as victim_name 
            FROM incidents i
            LEFT JOIN categories c ON i.category_id = c.id
            LEFT JOIN users v ON i.victim_id = v.id
            ORDER BY i.created_at DESC
        ";
        $incidents = Incident::fetchAll($sql);

        // Write Rows
        foreach ($incidents as $inc) {
            fputcsv($output, [
                $inc['id'],
                $inc['created_at'],
                $inc['victim_name'],
                $inc['category_name'],
                $inc['status'],
                $inc['assigned_responder_id'] ?? 'Unassigned',
                $inc['latitude'] . ', ' . $inc['longitude']
            ]);
        }
        
        fclose($output);
        exit; // Stop framework execution so no HTML is appended to the CSV
    }
}