<?php // update_stage_status.php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Load configuration using the 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.");
}

// Initialize response variable
$return = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
try {
// Retrieve parameters from POST request
$master_report_id = $_POST['master_report_id'] ?? null;
$stage = $_POST['stage'] ?? null;
$new_status = $_POST['status'] ?? null; // Status can be "ongoing" or "complete"
$board_id = $_POST['board_id'] ?? null; // Specific board to update for stage 4, if provided

// Check if necessary parameters are provided
if (empty($master_report_id) || empty($stage) || empty($new_status)) {
echo json_encode(['success' => false, 'message' => 'Missing required parameters.']);
exit;
}

// Handle stage 4 where board_id is required
if ($stage == 5 && empty($board_id)) {
echo json_encode(['success' => false, 'message' => 'Missing board ID for stage 5 update.']);
exit;
}

// Fetch the existing stage_status for the provided master_report_id
if ($stage == 5) {
// Update a specific board for stage 4
$query = "SELECT stage_status FROM elec_report WHERE master_report_id = ? AND board_id = ?";
$stmt = $con->prepare($query);
$stmt->bind_param("si", $master_report_id, $board_id);
} else {
// Update the report for stages 1-3 (no need for board_id)
$query = "SELECT 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();
$row = $result->fetch_assoc();
$stmt->close();

// Decode the current stage_status if it exists
$stage_status = !empty($row['stage_status']) ? json_decode($row['stage_status'], true) : [];

// Update the stage status for the specific stage
$stage_status[$stage] = $new_status; // Update the status of the requested stage

// Convert the updated stage_status back to JSON
$updated_stage_status = json_encode($stage_status, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

// Update the row in the database with the new stage status
if ($stage == 5) {
// For stage 4, update for the specific board
$update_query = "UPDATE elec_report SET stage_status = ? WHERE master_report_id = ? AND board_id = ?";
$stmt = $con->prepare($update_query);
$stmt->bind_param("ssi", $updated_stage_status, $master_report_id, $board_id);
} else {
// For stages 1-3, update for the entire report (no board_id needed)
$update_query = "UPDATE elec_report SET stage_status = ? WHERE master_report_id = ?";
$stmt = $con->prepare($update_query);
$stmt->bind_param("ss", $updated_stage_status, $master_report_id);
}

if ($stmt->execute()) {
echo json_encode([
'success' => true,
'message' => 'Stage status updated successfully.',
]);
} else {
echo json_encode(['success' => false, 'message' => 'Failed to update stage status.']);
}
$stmt->close();

} catch (Exception $e) {
// Log the error
echo json_encode(['success' => false, 'message' => 'An unexpected error occurred: ' . $e->getMessage()]);
}
}

exit;?>