<?php
session_start();
require_once '../includes/config.php';

try {
    $reportNumber = $_POST['report_number'] ?? '';
    $reportDate = $_POST['report_date'] ?? '';
    $reportTime = $_POST['report_time'] ?? '';
    $informantName = $_POST['informant_name'] ?? '';
    $contactNo = $_POST['contact_no'] ?? '';
    $subject = $_POST['subject'] ?? '';
    $recordingOfficer = $_POST['recording_officer'] ?? '';

    // Directories
    $photoDir = '../uploads/incidents/photos/';
    $videoDir = '../uploads/incidents/videos/';
    @mkdir($photoDir, 0777, true);
    @mkdir($videoDir, 0777, true);

    // Uploads
    $photos = [];
    if (!empty($_FILES['photos']['name'][0])) {
        foreach ($_FILES['photos']['name'] as $i => $name) {
            $tmp = $_FILES['photos']['tmp_name'][$i];
            $newName = time() . '_' . basename($name);
            if (move_uploaded_file($tmp, $photoDir . $newName)) {
                $photos[] = $newName;
            }
        }
    }

    $videos = [];
    if (!empty($_FILES['videos']['name'][0])) {
        foreach ($_FILES['videos']['name'] as $i => $name) {
            $tmp = $_FILES['videos']['tmp_name'][$i];
            $newName = time() . '_' . basename($name);
            if (move_uploaded_file($tmp, $videoDir . $newName)) {
                $videos[] = $newName;
            }
        }
    }

    // Insert
    $stmt = $pdo->prepare("INSERT INTO incident_reports (
        report_number, report_date, report_time, informant_name,
        contact_no, subject, recording_officer, photo, video
    ) VALUES (
        :report_number, :report_date, :report_time, :informant_name,
        :contact_no, :subject, :recording_officer, :photo, :video
    )");

    $stmt->execute([
        ':report_number' => $reportNumber,
        ':report_date' => $reportDate,
        ':report_time' => $reportTime,
        ':informant_name' => $informantName,
        ':contact_no' => $contactNo,
        ':subject' => $subject,
        ':recording_officer' => $recordingOfficer,
        ':photo' => json_encode($photos),
        ':video' => json_encode($videos)
    ]);

    $_SESSION['toast'] = ['message' => '✅ Report submitted.'];
    header("Location: view_incidents.php");
    exit;

} catch (Exception $e) {
    echo "<h4 style='color:red;'>Error: " . htmlspecialchars($e->getMessage()) . "</h4>";
}
?>
