<?php
// save_schedule_of_inspection.php

// Enable error reporting for development (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

header('Content-Type: application/json');

// Retrieve basic parameters from POST
$clientnumber = $_POST['clientnumber'] ?? '';
$report_id = trim($_POST['report_id'] ?? '');
$is_update = $_POST['is_update'] ?? false; // Flag indicating whether it's an update or new report
$master_report_id = $_POST['master_report_id'] ?? null; // We expect the master_report_id here

// For Stage 2, set the new stage status (e.g. "pending")
$new_stage_status = "ongoing";

// Build the schedule array from POST data (using flat field names)
$schedule = [
    'earthing_arrangement'    => $_POST['earthing_arrangement'] ?? '',
    'system_type'             => $_POST['system_type'] ?? '',
    'live_conductors_AC'      => $_POST['live_conductors_AC'] ?? '',
    'live_conductors_DC'      => $_POST['live_conductors_DC'] ?? '',
    'polarity_verified'       => !empty($_POST['polarity_verified']) ? 1 : 0,
    'normal_voltage'          => $_POST['normal_voltage'] ?? '',
    'nominal_frequency'       => $_POST['nominal_frequency'] ?? '',
    'pfc'                     => $_POST['pfc'] ?? '',
    'ze'                      => $_POST['ze'] ?? '',
    'num_sources'             => $_POST['num_sources'] ?? '',
    'encMeas'                 => $_POST['encMeas'] ?? '',
    'protective_device_bs_en' => $_POST['protective_device_bs_en'] ?? '',
    'protective_device_type'  => $_POST['protective_device_type'] ?? '',
    'protective_device_rating'=> $_POST['protective_device_rating'] ?? '',
    
    // SECTION J: Particulars of Installation
    'distributors_facility_checked' => !empty($_POST['distributors_facility_checked']) ? 1 : 0,
    'distributors_facility_type'      => $_POST['distributors_facility_type'] ?? '',
    'distributors_facility_location'  => $_POST['distributors_facility_location'] ?? '',
    'distributors_facility_resistance'=> $_POST['distributors_facility_resistance'] ?? '',
    'installation_electrode_electrode'=> $_POST['installation_electrode_electrode'] ?? '',
    'installation_electrode_type'     => $_POST['installation_electrode_type'] ?? '',
    'installation_electrode_resistance'=> $_POST['installation_electrode_resistance'] ?? '',
    'earthing_conductor_material'     => $_POST['earthing_conductor_material'] ?? '',
    'earthing_conductor_size'         => $_POST['earthing_conductor_size'] ?? '',
    'earthing_conductor_verified'     => !empty($_POST['earthing_conductor_verified']) ? 1 : 0,
    'bonding_conductor_material'      => $_POST['bonding_conductor_material'] ?? '',
    'bonding_conductor_size'          => $_POST['bonding_conductor_size'] ?? '',
    'bonding_conductor_verified'      => !empty($_POST['bonding_conductor_verified']) ? 1 : 0,
    'services_water_service'          => !empty($_POST['services_water_service']) ? 1 : 0,
    'services_gas_service'            => !empty($_POST['services_gas_service']) ? 1 : 0,
    'services_oil_service'            => !empty($_POST['services_oil_service']) ? 1 : 0,
    'services_structural_steel'       => !empty($_POST['services_structural_steel']) ? 1 : 0,
    'services_lightning_protection'   => !empty($_POST['services_lightning_protection']) ? 1 : 0,
    'services_other_services'         => !empty($_POST['services_other_services']) ? 1 : 0,
    
    // SECTION II: Main Switch / Switch-Fuse / Circuit-Breaker / RCD
    'main_switch_location'          => $_POST['main_switch_location'] ?? '',
    'main_switch_poles'             => $_POST['main_switch_poles'] ?? '',
    'main_switch_bsen'              => $_POST['main_switch_bsen'] ?? '',
    'main_switch_current_rating'    => $_POST['main_switch_current_rating'] ?? '',
    'main_switch_fuse_rating'       => $_POST['main_switch_fuse_rating'] ?? '',
    'main_switch_voltage_rating'    => $_POST['main_switch_voltage_rating'] ?? '',
    'main_switch_residual_current'  => $_POST['main_switch_residual_current'] ?? '',
    'main_switch_time_delay'        => $_POST['main_switch_time_delay'] ?? '',
    'main_switch_operating_time'    => $_POST['main_switch_operating_time'] ?? ''
];

$jsonData = json_encode($schedule, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if ($jsonData === false) {
    echo json_encode(['success' => false, 'message' => 'Failed to encode JSON data.']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Branch A: Update an existing report group (if report_id is provided)
        if ($is_update == "true" && !empty($master_report_id)) {
            // Update the report group using the master_report_id
            $update_query = "UPDATE elec_report 
                             SET schedule_of_inspection = ?, 
                                 stage_status = JSON_SET(COALESCE(stage_status, '{}'), '$.\"2\"', ?)
                             WHERE master_report_id = ?";
            $stmt = $con->prepare($update_query);
            if (!$stmt) {
                echo json_encode(['success' => false, 'message' => 'Database error during update.']);
                exit;
            }
            $stmt->bind_param("sss", $jsonData, $new_stage_status, $master_report_id);
            if ($stmt->execute()) {
                $stmt->close();
                echo json_encode([
                    'success'   => true,
                    'message'   => 'Schedule of inspection updated successfully.',
                ]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to save schedule.']);
                exit;
            }
        }
        // Branch B: New report creation (if no report_id or master_report_id is provided)
        else {
            // Expect board_list to be provided as a JSON string.
            $board_list_json = $_POST['board_list'] ?? '';
            if (empty($board_list_json)) {
                echo json_encode(['success' => false, 'message' => 'Board list is missing for new report creation.']);
                exit;
            }
            $board_list = json_decode($board_list_json, true);
            if (!is_array($board_list) || empty($board_list)) {
                echo json_encode(['success' => false, 'message' => 'Invalid board list.']);
                exit;
            }

            // Generate a new master_report_id for this group of boards
            $master_report_id = uniqid('mr_', true);
            $errors = [];
            // Insert a new row for each board in the board list
            foreach ($board_list as $board_item) {
                $b_id = (is_array($board_item) && isset($board_item['board_id']))
                      ? intval($board_item['board_id'])
                      : intval($board_item);
                $insert_query = "INSERT INTO elec_report 
                                 (board_id, clientnumber, locnumber, schedule_of_inspection, status, master_report_id, stage_status) 
                                 VALUES (?, ?, ?, ?, 'active', ?, JSON_OBJECT('2', ?))";
                $stmt = $con->prepare($insert_query);
                if (!$stmt) {
                    $errors[] = "Board $b_id: DB error during insert preparation: " . $con->error;
                    continue;
                }
                $stmt->bind_param("isssss", $b_id, $clientnumber, $locnumber, $jsonData, $master_report_id, $new_stage_status);
                if (!$stmt->execute()) {
                    $errors[] = "Board $b_id: " . $stmt->error;
                }
                $stmt->close();
            }

            if (!empty($errors)) {
                echo json_encode(['success' => false, 'message' => "Errors during insert: " . implode("; ", $errors)]);
                exit;
            }

           
            echo json_encode([
                'success' => true,
                'message' => 'Schedule of inspection saved and new report created successfully.',
                'master_report_id' => $master_report_id
            ]);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'An unexpected error occurred: ' . $e->getMessage()]);
    }
}
exit;
?>