<?php

require '../config/database.php';
session_start();

header('Content-Type: application/json');

if (!isset($_FILES['file'])) {
    echo json_encode([
        "status" => "error",
        "message" => "File required"
    ]);
    exit;
}

$concernId = intval($_POST['concern_id']);
$userId = $_SESSION['user_id'];

$uploadDir = "../../uploads/concerns/";

if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

$filename = uniqid() . "_" . basename($_FILES["file"]["name"]);
$target = $uploadDir . $filename;

if (!move_uploaded_file($_FILES["file"]["tmp_name"], $target)) {
    echo json_encode([
        "status" => "error",
        "message" => "Upload failed"
    ]);
    exit;
}

$stmt = $pdo->prepare("
INSERT INTO safety_concern_evidence
(concern_id, uploaded_by, file_path, uploaded_at)
VALUES (?, ?, ?, NOW())
");

$stmt->execute([
    $concernId,
    $userId,
    $filename
]);

echo json_encode([
    "status" => "success"
]);