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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $report_id = intval($_POST['master_report_id'] ?? 0);
    $stage = intval($_POST['stage'] ?? 0);
    $status = $_POST['status'] ?? '';
    $is_update = isset($_POST['is_update']) ? $_POST['is_update'] : false;
    if (!$report_id || !$stage || empty($status)) {
        echo json_encode(['success' => false, 'message' => 'Missing required parameters.']);
        exit;
    }

    // Fetch current stage status
    $query = "SELECT stage_status FROM elec_report WHERE master_report_id = ? LIMIT 1";
    $stmt = $con->prepare($query);
    $stmt->bind_param("i", $report_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    $stmt->close();

    $stageStatus = !empty($row['stage_status']) ? json_decode($row['stage_status'], true) : [];

    // Update status for the given stage
    $stageStatus[$stage] = $status;

    // Save updated status
    $query = "UPDATE elec_report SET stage_status = ? WHERE master_report_id = ?";
    $stmt = $con->prepare($query);
    $updatedStatus = json_encode($stageStatus, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    $stmt->bind_param("si", $updatedStatus, $report_id);

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

    $stmt->close();
    exit;
}
?>