<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$data = json_decode(file_get_contents('php://input'), true);

// Load the configuration file using the tenant parameter
$tenant = $data['tenant'] ?? null;
require_once('../../../' . $tenant . '/config.php');

// Get the JSON data sent from the JavaScript
$master_report_id = $data['master_report_id'] ?? null;
$extent = $data['extent'] ?? null;
$generalCondition = $data['generalCondition'] ?? null;
$installationSummary = $data['installationSummary'] ?? null;
$recommendations = $data['recommendations'] ?? null;
$surveyor = $data['surveyor'] ?? null;
$inspectionDates = $data['inspectionDates'] ?? null;
$inspectioNextDate = $data['inspectioNextDate'] ?? null;

if (!$master_report_id) {
    echo json_encode(['success' => false, 'message' => 'Master report ID is missing.']);
    exit;
}

// Check for NULL values and replace with empty string if necessary
$generalCondition = $generalCondition ?? ''; // Default to empty string if NULL
$installationSummary = $installationSummary ?? ''; // Default to empty string if NULL
$recommendations = $recommendations ?? ''; // Default to empty string if NULL
$surveyor = $surveyor ?? ''; // Default to empty string if NULL
$inspectionDates = $inspectionDates ?? ''; // Default to empty string if NULL
$inspectioNextDate = $inspectioNextDate ?? ''; // Default to empty string if NULL

// Update the installation details and other fields for the given master_report_id
$updateQuery = "UPDATE elec_report SET 
                installation_details = JSON_SET(installation_details, 
                    '$.extent', ?, 
                    '$.inspectionDates', ?),
                general_condition = ?, 
                summary_condition = ?, 
                overall_recommendation = ?, 
                surveyor_id = ?, 
                inspection_date = ?, 
                inspectionNextDate = ?, 
                status = 'complete'
                WHERE master_report_id = ?";

// Prepare the statement
$stmt = $con->prepare($updateQuery);

// Adjusting parameter types dynamically for NULL
$stmt->bind_param("ssssssssi", 
    $extent, 
    $inspectionDates, 
    $generalCondition, 
    $installationSummary, 
    $recommendations, 
    $surveyor, 
    $inspectionDates, 
    $inspectioNextDate, 
    $master_report_id
);

if ($stmt->execute()) {
    // Successfully updated the data, now mark all rows as 'complete'
    $markCompleteQuery = "UPDATE elec_report SET status = 'complete' WHERE master_report_id = ?";
    $stmt2 = $con->prepare($markCompleteQuery);
    $stmt2->bind_param("s", $master_report_id);
    $stmt2->execute();

    echo json_encode(['success' => true, 'message' => 'Report finalized and marked as complete.']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to finalize report.']);
}

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