<?php
require 'config.php'; // Include database connection

header("Content-Type: application/json");
$conn = getDbConnection();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // ✅ Log incoming request
    file_put_contents('incident_report_debug.log', "POST Data:\n" . print_r($_POST, true), FILE_APPEND);
    file_put_contents('incident_report_debug.log', "FILES Data:\n" . print_r($_FILES, true), FILE_APPEND);

    // ✅ Validate required fields
    $required_fields = ['token', 'real_name', 'org_id', 'site_id', 'incident_type', 'incident_description', 'corrective_action', 'severity'];
    foreach ($required_fields as $field) {
        if (empty($_POST[$field])) {
            http_response_code(400);
            echo json_encode(["success" => false, "message" => "Missing required field: $field"]);
            exit;
        }
    }

    $token = $_POST['token'];
    $real_name = $_POST['real_name'];
    $org_id = intval($_POST['org_id']);
    $site_id = intval($_POST['site_id']);
    $incident_type = $_POST['incident_type'];
    $custom_incident = $_POST['custom_incident'] ?? null;
    $incident_description = $_POST['incident_description'];
    $corrective_action = $_POST['corrective_action'];
    $severity = $_POST['severity'];

    // ✅ Validate severity
    $validSeverities = ["Low", "Medium", "High"];
    if (!in_array($severity, $validSeverities)) {
        http_response_code(400);
        echo json_encode(["success" => false, "message" => "Invalid severity level"]);
        exit;
    }

    // ✅ Validate token
    $stmt = $conn->prepare("SELECT user_id FROM users WHERE token = ?");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();

    if (!$user) {
        http_response_code(403);
        echo json_encode(["success" => false, "message" => "Invalid token"]);
        exit;
    }

    $user_id = $user['user_id'];

    // ✅ Handle file uploads
    $upload_dir = '../uploads/incidents/';
    if (!file_exists($upload_dir) && !mkdir($upload_dir, 0777, true)) {
        http_response_code(500);
        echo json_encode(["success" => false, "message" => "Failed to create upload directory"]);
        exit;
    }

    function handle_file_upload($file, $prefix, $upload_dir) {
        if ($file && $file['error'] === UPLOAD_ERR_OK) {
            $file_path = $upload_dir . uniqid($prefix . '_') . '_' . basename($file['name']);
            if (move_uploaded_file($file['tmp_name'], $file_path)) {
                return $file_path;
            }
        }
        return null;
    }

    $incident_image_path = handle_file_upload($_FILES['incident_image'] ?? null, 'incident', $upload_dir);
    $corrective_image_path = handle_file_upload($_FILES['corrective_image'] ?? null, 'corrective', $upload_dir);

    // ✅ Save to database
    $stmt = $conn->prepare("INSERT INTO incident_reports (user_id, real_name, org_id, site_id, incident_type, custom_incident, incident_description, incident_image, corrective_action, corrective_image, severity, timestamp) 
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
    $stmt->bind_param("isisissssss", $user_id, $real_name, $org_id, $site_id, $incident_type, $custom_incident, $incident_description, $incident_image_path, $corrective_action, $corrective_image_path, $severity);

    if ($stmt->execute()) {
        http_response_code(200);
        echo json_encode([
            "success" => true,
            "message" => "Incident reported successfully",
            "incident_image_path" => $incident_image_path,
            "corrective_image_path" => $corrective_image_path
        ]);
    } else {
        http_response_code(500);
        echo json_encode(["success" => false, "message" => "Database error: " . $stmt->error]);
    }

    $stmt->close();
    $conn->close();
} else {
    http_response_code(405);
    echo json_encode(["success" => false, "message" => "Invalid request method"]);
}
