<?php

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

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode([
        "status" => "error",
        "message" => "Unauthorized"
    ]);
    exit;
}

$userId = $_SESSION['user_id'];

try {

    $stmt = $pdo->prepare("
        SELECT
            c.id,
            c.title,
            c.description,
            c.hazard_level,
            c.status,
            c.created_at,
            c.due_date,

            s.section_name,

            u.first_name AS assigned_first,
            u.last_name AS assigned_last,

            creator.first_name AS creator_first,
            creator.last_name AS creator_last

        FROM safety_concerns c

        LEFT JOIN sections s
            ON c.section_id = s.id

        LEFT JOIN users u
            ON c.assigned_user_id = u.id

        LEFT JOIN users creator
            ON c.created_by = creator.id

        ORDER BY c.created_at DESC
    ");

    $stmt->execute();

    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        "status" => "success",
        "data" => [
            "concerns" => $rows
        ]
    ]);

} catch (Exception $e) {

    echo json_encode([
        "status" => "error",
        "message" => $e->getMessage()
    ]);

}