<?php
if (file_exists('../../../' . $_POST['tenant'] . '/config.php')) {
    require_once('../../../' . $_POST['tenant'] . '/config.php');
} elseif (file_exists('/config.php')) {
    require_once('/config.php');
} else {
    die(json_encode(['success' => false, 'message' => 'Configuration file not found.']));
}

$board_id = intval($_POST['board_id']);
if (!$board_id) {
    die(json_encode(['success' => false, 'message' => 'Board ID is required.']));
}

try {
    // Corrected query without extra comma and ordering by inspection_date
    $query = "
        SELECT 
            report_id,
            report_reference,
            inspection_date
        FROM elec_report
        WHERE board_id = ?
        AND status= 'complete'
        ORDER BY inspection_date DESC
    ";

    $stmt = $con->prepare($query);
    if (!$stmt) {
        die(json_encode(['success' => false, 'message' => 'Database error: ' . $con->error]));
    }
    $stmt->bind_param('i', $board_id);
    $stmt->execute();
    $result = $stmt->get_result();

    $reports = [];
    while ($row = $result->fetch_assoc()) {
        $reports[] = $row;
    }

    echo json_encode(['success' => true, 'reports' => $reports]);
} catch (Exception $e) {
    error_log("Error fetching reports: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Failed to fetch reports.']);
}
?>