<?php
// get_report_status.php

require_once('../../../' . $_REQUEST['tenant'] . '/config.php');

if (!isset($_GET['master_report_id']) || empty($_GET['master_report_id'])) {
    echo json_encode(['success' => false, 'message' => 'Master Report ID missing.']);
    exit;
}

$master_report_id = $_GET['master_report_id'];  // Get the report ID

// Retrieve stage_status from all rows for the specific master_report_id
$query = "SELECT board_id, stage_status FROM elec_report WHERE master_report_id = ?";
$stmt = $con->prepare($query);
$stmt->bind_param("s", $master_report_id);  // Bind the report ID
$stmt->execute();
$result = $stmt->get_result();

$reportStatus = [
    'stage_1_4' => [
        1 => 'empty',  // Default to empty if not set
        2 => 'empty',
        3 => 'empty',
        4 => 'empty',
    ],  // Array to hold the common status for stages 1-3
    'stage_5'   => []   // Array to hold the board-specific stage 4 status
];

while ($row = $result->fetch_assoc()) {
    $board_id = $row['board_id'];
    $stage_status = !empty($row['stage_status']) ? json_decode($row['stage_status'], true) : [];

    // For stages 1-3, store the common status for all boards
    if (isset($stage_status["1"])) {
        $reportStatus['stage_1_4'][1] = $stage_status["1"];
    }
    if (isset($stage_status["2"])) {
        $reportStatus['stage_1_4'][2] = $stage_status["2"];
    }
    if (isset($stage_status["3"])) {
        $reportStatus['stage_1_4'][3] = $stage_status["3"];
    }
     if (isset($stage_status["4"])) {
        $reportStatus['stage_1_4'][4] = $stage_status["4"];
    }

    // Check if stage 4 exists for the board and add it to the stage_4 status
    if (isset($stage_status["5"])) {
        $reportStatus['stage_5'][$board_id] = $stage_status["5"];
    } else {
        $reportStatus['stage_5'][$board_id] = 'empty'; // Set to 'empty' if no value for stage 4
    }
}

$stmt->close();

// Output the result in JSON format
echo json_encode([
    'success' => true,
    'data' => $reportStatus  // Return the status per board and the common status for stages 1-3
]);

exit;
?>