<?php
// load_stage.php
// Log all request data for debugging purposes.
//file_put_contents("debug_log.txt", "Received Data: " . print_r($_REQUEST, true) . PHP_EOL, FILE_APPEND);

// Load configuration file using tenant parameter.
if (file_exists('../../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../../' . $_REQUEST['tenant'] . '/config.php');
} elseif (file_exists('/config.php')) {
    require_once('/config.php');
} else {
    die("Configuration file not found.");
}

// Retrieve parameters from POST or GET.
$tenant     = $_REQUEST['tenant'] ?? '';
$stage     = isset($_REQUEST['stage']) ? $_REQUEST['stage'] : '';
$report_id = isset($_REQUEST['report_id']) ? $_REQUEST['report_id'] : '';
$clientnumber = $_REQUEST['clientnumber'] ?? '';
$locnumber = isset($_REQUEST['locnumber']) ? $_REQUEST['locnumber'] : '';
$is_update = isset($_POST['is_update']) ? $_POST['is_update'] : false;

// --- NEW: Process board_list if available ---
$board_list_json = $_REQUEST['board_list'] ?? '';
$board_list = [];
if (!empty($board_list_json)) {
    $board_list = json_decode($board_list_json, true);
    // If board_list exists but no board_id, use the first board from the list.
    if (empty($_REQUEST['board_id']) && !empty($board_list)) {
        $board_id = isset($board_list[0]['board_id']) ? intval($board_list[0]['board_id']) : 0;
    }
} else {
    $board_list = [];
}

// Instead of using board_id, we now require a board_list parameter.
if (empty($_REQUEST['board_list'])) {
    die("Invalid request. Board list is missing. Debug: " . print_r($_REQUEST, true));
} else {
    $board_list = json_decode($_REQUEST['board_list'], true);
    if (!is_array($board_list) || empty($board_list)) {
        die("Invalid board list. Debug: " . print_r($_REQUEST, true));
    }
}

// For convenience, you can expose the decoded board list as a global variable.
$GLOBALS['ALL_BOARD_LIST'] = $board_list;

// Helper function: Check for an incomplete report for a given board.
function check_incomplete_report($board_id) {
    global $con;
    // Look for a report by active status and return the master_report_id if it exists
    $query = "SELECT master_report_id FROM elec_report WHERE board_id = ? AND status = 'active'";
    $stmt = $con->prepare($query);
    $stmt->bind_param("i", $board_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $data = $result->fetch_assoc();
    $stmt->close();
    return $data;
}

// First, try to get board_id from POST/GET as before.
$board_id = isset($_POST['board_id']) ? $_POST['board_id'] : (isset($_GET['board_id']) ? $_GET['board_id'] : '');

// If board_id is empty, try to decode the board_list and use the first board's ID.
if (empty($board_id)) {
    if (!empty($_REQUEST['board_list'])) {
        $board_list = json_decode($_REQUEST['board_list'], true);
        if (is_array($board_list) && count($board_list) > 0) {
            $board_id = intval($board_list[0]['board_id'] ?? 0);
        }
    }
}

// If board_id is still empty, then it's an invalid request.
if (empty($board_id)) {
    die("Invalid request. Debug: " . print_r($_REQUEST, true));
}

// If report_id is empty, try to get the master_report_id for the given board.
if (empty($report_id)) {
    $incomplete_report = check_incomplete_report($board_id);
    // If master_report_id is found, use it
    if (!empty($incomplete_report['master_report_id'])) {
        $report_id = $incomplete_report['master_report_id'];
    }
} else {
    // If the report_id was passed, we use that directly
    $report_id = $report_id;
    $incomplete_report['master_report_id']=$report_id;
}

// Logging function for errors.
function logError($errorMessage) {
    $errorLog = 'error_log.txt';
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($errorLog, "[$timestamp] $errorMessage\n", FILE_APPEND);
}

// Dispatch to the correct stage based on $stage.
switch ($stage) {
    case 1:
        include 'stages/installation_details.php';
        break;
    case 'save_stage_1':
        include 'stages/save_installation_details.php';
        break;
    case 2:
        include 'stages/schedule_of_inspection.php';
        break;
    case 'save_stage_2':
        include 'stages/save_schedule_of_inspection.php';
        break;
    case 3:
        include 'stages/condition_report.php';
        break;
    case 'save_stage_3':
        include 'stages/save_condition_report.php';
        break;
    case 4:
        include 'stages/observations.php';        // your new observations input page
    break;
    case 'save_stage_4':
        include 'stages/save_observations.php';  // save into elec_report.observations
        break;
    case 5:
        include 'stages/inspection_test_results.php';
        break;
    case 'save_stage_5':
        include 'stages/save_inspection_test_results.php';
    break;
    default:
        echo '<p>Select a valid stage.</p>';
        break;
}
?>