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

if (!isset($_POST['incident_id'])) {
    $_SESSION['toast'] = ['message' => 'Invalid request.'];
    header("Location: command_center.php");
    exit;
}

$id = $_POST['incident_id'];
$title = $_POST['title'];
$description = $_POST['description'];
$status = $_POST['status'];

$uploadPhotoDir = '../uploads/incidents/photos/';
$uploadVideoDir = '../uploads/incidents/videos/';
@mkdir($uploadPhotoDir, 0777, true);
@mkdir($uploadVideoDir, 0777, true);

// Get current incident to fetch existing photos/videos
$stmt = $pdo->prepare("SELECT photo, video FROM incident_reports WHERE id = ?");
$stmt->execute([$id]);
$incident = $stmt->fetch();

$currentPhotos = json_decode($incident['photo'] ?? '[]');
$currentVideos = json_decode($incident['video'] ?? '[]');

// Remove selected photos
if (!empty($_POST['delete_photos'])) {
    foreach ($_POST['delete_photos'] as $deleteFile) {
        $filePath = $uploadPhotoDir . basename($deleteFile);
        if (file_exists($filePath)) unlink($filePath);
        $currentPhotos = array_filter($currentPhotos, fn($p) => $p !== $deleteFile);
    }
}

// Remove selected videos
if (!empty($_POST['delete_videos'])) {
    foreach ($_POST['delete_videos'] as $deleteVideo) {
        $filePath = $uploadVideoDir . basename($deleteVideo);
        if (file_exists($filePath)) unlink($filePath);
        $currentVideos = array_filter($currentVideos, fn($v) => $v !== $deleteVideo);
    }
}

// Handle new photo uploads
if (!empty($_FILES['photos']['name'][0])) {
    foreach ($_FILES['photos']['name'] as $key => $name) {
        $tmpName = $_FILES['photos']['tmp_name'][$key];
        $newName = time() . '_' . basename($name);
        $target = $uploadPhotoDir . $newName;
        if (move_uploaded_file($tmpName, $target)) {
            $currentPhotos[] = $newName;
        }
    }
}

// Handle new video uploads
if (!empty($_FILES['videos']['name'][0])) {
    foreach ($_FILES['videos']['name'] as $key => $name) {
        $tmpName = $_FILES['videos']['tmp_name'][$key];
        $newName = time() . '_' . basename($name);
        $target = $uploadVideoDir . $newName;
        if (move_uploaded_file($tmpName, $target)) {
            $currentVideos[] = $newName;
        }
    }
}

$photoJSON = json_encode(array_values($currentPhotos));
$videoJSON = json_encode(array_values($currentVideos));

// Update record
$update = $pdo->prepare("UPDATE incident_reports SET title = ?, description = ?, status = ?, photo = ?, video = ?, updated_at = NOW() WHERE id = ?");
$update->execute([$title, $description, $status, $photoJSON, $videoJSON, $id]);

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