<?php
// Error handling to capture issues as JSON
function sendErrorToConsole($errno, $errstr, $errfile, $errline)
{
    $errorData = [
        'success' => false,
        'message' => 'PHP Error',
        'error' => [
            'number' => $errno,
            'string' => $errstr,
            'file' => $errfile,
            'line' => $errline,
        ],
    ];

    // Log the error to a file
    //file_put_contents('debug_errors.log', json_encode($errorData) . PHP_EOL, FILE_APPEND);

    // Output the error as JSON
    header('Content-Type: application/json');
    echo json_encode($errorData);
    exit;
}
set_error_handler('sendErrorToConsole');

// Start output buffering to capture any unexpected output
ob_start();

// Debug: Log POST data
//file_put_contents('debug_post.log', print_r($_POST, true));

// Include tenant and core configuration files
if (file_exists('../../../' . $_POST['tenant'] . '/config.php')) {
    require_once('../../../' . $_POST['tenant'] . '/config.php');
}

if (file_exists('/config.php')) {
    require_once('/config.php');
}

// Include functions
require_once('elec_distro_functions.php');

// Validate required POST fields
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_POST['clientnumber']) || empty($_POST['siteList']) || empty($_POST['board_name'])) {
    // Send error if required fields are missing
    echo json_encode(['success' => false, 'message' => 'Invalid input or missing required fields.']);
    exit;
}


// Sanitize and convert POST data
$clientnumber = filter_input(INPUT_POST, 'clientnumber', FILTER_VALIDATE_INT);
$locnumber = filter_input(INPUT_POST, 'siteList', FILTER_VALIDATE_INT);
$board_name = filter_input(INPUT_POST, 'board_name', FILTER_SANITIZE_STRING);
$reference = filter_input(INPUT_POST, 'reference', FILTER_SANITIZE_STRING);
$supply_from = filter_input(INPUT_POST, 'supply_from', FILTER_SANITIZE_STRING);
$polarity_confirmed = isset($_POST['polarity_confirmed']) ? 1 : 0;
$phase_sequence_confirmed = isset($_POST['phase_sequence_confirmed']) ? 1 : 0;
$manufacturer = filter_input(INPUT_POST, 'manufacturer', FILTER_SANITIZE_STRING);
$board_type = filter_input(INPUT_POST, 'board_type', FILTER_SANITIZE_STRING);
$installation_date = filter_input(INPUT_POST, 'installation_date', FILTER_SANITIZE_STRING);
$surge_protection_type = filter_input(INPUT_POST, 'surge_protection_type', FILTER_VALIDATE_INT);
$surge_protection_part_no = filter_input(INPUT_POST, 'surge_protection_part_no', FILTER_SANITIZE_STRING);
$surge_protection_functional = isset($_POST['surge_protection_functional']) ? 1 : 0;
$surge_protection_imax = filter_input(INPUT_POST, 'surge_protection_imax', FILTER_VALIDATE_FLOAT);
$bs_type = filter_input(INPUT_POST, 'bs_type', FILTER_SANITIZE_STRING);
$rating = filter_input(INPUT_POST, 'rating', FILTER_VALIDATE_INT);
$poles = filter_input(INPUT_POST, 'poles', FILTER_VALIDATE_INT);
$mccb_type = filter_input(INPUT_POST, 'mccb_type', FILTER_SANITIZE_STRING);
$associated_rcd = filter_input(INPUT_POST, 'associated_rcd', FILTER_SANITIZE_STRING);
$trip_current = filter_input(INPUT_POST, 'trip_current', FILTER_VALIDATE_FLOAT);
$trip_time_1x = filter_input(INPUT_POST, 'trip_time_1x', FILTER_VALIDATE_FLOAT);
$zdb = filter_input(INPUT_POST, 'zdb', FILTER_VALIDATE_FLOAT);
$pfc_pscc = filter_input(INPUT_POST, 'pfc_pscc', FILTER_VALIDATE_FLOAT);
$voltage = filter_input(INPUT_POST, 'voltage', FILTER_VALIDATE_INT);
$circuit_mode = filter_input(INPUT_POST, 'circuit_mode', FILTER_SANITIZE_STRING);

// Debug: Log sanitized data
file_put_contents('debug_sanitized.log', print_r(get_defined_vars(), true));

// Insert the data using `add_new_distro`
$new_board_id = add_new_distro(
    $clientnumber,
    $locnumber,
    $board_name,
    $reference,
    $supply_from,
    $polarity_confirmed,
    $phase_sequence_confirmed,
    $manufacturer,
    $board_type,
    $installation_date,
    $surge_protection_type,
    $surge_protection_part_no,
    $surge_protection_functional,
    $surge_protection_imax,
    $bs_type,
    $rating,
    $poles,
    $associated_rcd,
    $trip_current,
    $trip_time_1x,
    $mccb_type,
    $zdb,
    $pfc_pscc,
    $voltage,
        $circuit_mode
);

// Capture unexpected output
$unexpectedOutput = ob_get_clean();

if ($new_board_id) {
    // Success response
    echo json_encode([
        'success' => true,
        'new_board_id' => $new_board_id,
        'clientnumber' => $clientnumber,
        'unexpected_output' => $unexpectedOutput, // Log unexpected output if any
    ]);
} else {
    // Error response
    echo json_encode([
        'success' => false,
        'message' => 'Error creating the distribution board.',
        'unexpected_output' => $unexpectedOutput,
        'debug_log' => file_get_contents('debug_errors.log'), // Include debug logs
    ]);
}
?>