<?php
// get_stage_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 master report ID

// Retrieve stage_status for all stages and board-specific stage 4
$query = "
    SELECT board_id, stage_status 
    FROM elec_report 
    WHERE master_report_id = ?
";
$stmt = $con->prepare($query);
$stmt->bind_param("s", $master_report_id);
$stmt->execute();
$result = $stmt->get_result();

$stageStatuses = [
    'stage_1_4' => [],
    'stage_5'   => []
];

// Iterate through the result to capture stage statuses for stages 1-3 and individual board statuses for stage 4
while ($row = $result->fetch_assoc()) {
    $board_id = $row['board_id'];
    $stage_status = !empty($row['stage_status']) ? json_decode($row['stage_status'], true) : [];

    // Add the stage status for stages 1-3 (common to all boards)
    if (isset($stage_status["1"])) {
        $stageStatuses['stage_1_4'][1] = $stage_status["1"];
    }
    if (isset($stage_status["2"])) {
        $stageStatuses['stage_1_4'][2] = $stage_status["2"];
    }
    if (isset($stage_status["3"])) {
        $stageStatuses['stage_1_4'][3] = $stage_status["3"];
    } if (isset($stage_status["4"])) {
        $stageStatuses['stage_1_4'][4] = $stage_status["4"];
    }

    // Add the board-specific stage 4 status
    if (isset($stage_status["5"])) {
        $stageStatuses['stage_5'][$board_id] = $stage_status["5"];
    }
}

$stmt->close();

// Return the results as JSON
echo json_encode([
    'success' => true,
    'data' => $stageStatuses
]);

exit;
?>