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

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['incident_id'])) {
    header('Location: command_center.php');
    exit;
}

$incidentId = intval($_POST['incident_id']);
$title = $_POST['title'] ?? '';
$description = $_POST['description'] ?? '';
$status = $_POST['status'] ?? 'pending';
$deletePhotos = $_POST['delete_photos'] ?? [];

$uploadDir = '../uploads/';
$newPhotos = [];

// Fetch existing photos
$stmt = $pdo->prepare("SELECT photo, video FROM incident_reports WHERE id = ?");
$stmt->execute([$incidentId]);
$current = $stmt->fetch(PDO::FETCH_ASSOC);
$currentPhotos = $current && $current['photo'] ? json_decode($current['photo'], true) : [];
$currentVideo = $current['video'] ?? null;

// Delete selected photos
if (!empty($deletePhotos)) {
    foreach ($deletePhotos as $file) {
        if (in_array($file, $currentPhotos)) {
            @unlink($uploadDir . $file);
        }
    }
    $currentPhotos = array_diff($currentPhotos, $deletePhotos);
}

// Upload new photos
if (!empty($_FILES['photos']['name'][0])) {
    foreach ($_FILES['photos']['tmp_name'] as $index => $tmpName) {
        $fileName = time() . '_' . basename($_FILES['photos']['name'][$index]);
        $targetPath = $uploadDir . $fileName;
        if (move_uploaded_file($tmpName, $targetPath)) {
            $currentPhotos[] = $fileName;
        }
    }
}

// Handle video replacement
if (isset($_FILES['video']) && $_FILES['video']['error'] === 0) {
    if ($currentVideo) {
        @unlink($uploadDir . $currentVideo);
    }
    $videoName = time() . '_' . basename($_FILES['video']['name']);
    if (move_uploaded_file($_FILES['video']['tmp_name'], $uploadDir . $videoName)) {
        $currentVideo = $videoName;
    }
}

// Update incident
$stmt = $pdo->prepare("UPDATE incident_reports SET title = ?, description = ?, status = ?, photo = ?, video = ? WHERE id = ?");
$stmt->execute([
    $title,
    $description,
    $status,
    json_encode(array_values($currentPhotos)),
    $currentVideo,
    $incidentId
]);

$_SESSION['toast'] = [
    'type' => 'success',
    'message' => 'Incident updated successfully.'
];
header('Location: command_center.php');
exit;
?>
