<?php 
ob_start(); // Start output buffering

require_once(ROOT_URL . '/includes/elec/elec_distro_functions.php');
require_once(ROOT_URL . '/includes/master/form_functions.php');
// Get action, distro_id, and clientnumber from URL parameters
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'define_board';
$clientnumber = isset($_REQUEST['clientnumber']) ? $_REQUEST['clientnumber'] : null;
$locnumber = 1;

if ($clientnumber) {
    // Display the form for defining a new board
    echo "<div class='container-fluid'>";
    echo "<h2 class='my-4'>Define New Distribution Board for " . getClientName($clientnumber) . "</h2>";
    echo "<form id='defineBoardForm' method='post'>";
    echo "<input type='hidden' name='define_board' value='1'>";
    echo "<input type='hidden' name='tenant' value='" . TENANT_URL . "'>";
    echo "<input type='hidden' name='clientnumber' value='{$clientnumber}'>";

    /* =======================================================
       Section: General Board Details 
       ======================================================= */
    echo "<div class='row'>";
    echo "<div class='card mb-4 col-12 col-md-8'>";
    echo "  <div class='card-header bg-primary text-light'>General Board Details</div>";
    echo "  <div class='card-body'>";
    echo "    <div class='row'>";


  echo "      <div class='col-md-6 mb-3'>";
  echo "<label for='circuit_mode'>Circuit layout</label>";
  echo "<select name='circuit_mode' id='circuit_mode' class='form-control'>";
    echo "<option value='LV' selected>3 Phase</option>";
    echo "<option value='SwitchBoard'>Single Phase</option>";
  echo "</select>";
echo "</div>";
    
    // Board Name and Reference
    echo "      <div class='col-md-6 mb-3'>";
    echo "        <label for='board_name' class='form-label'>Board Name</label>";
    echo "        <input type='text' class='form-control' id='board_name' name='board_name' required>";
    echo "      </div>";
    // Board location
    echo "      <div class='col-md-6 mb-3'>";
    echo "      <label for='locnumber' class='form-label'>Location</label>";
    echo        getSites2($clientnumber,0);
    echo "      </div>";
    
    echo "      <div class='col-md-6 mb-3'>";
    echo "        <label for='reference' class='form-label'>Reference</label>";
    echo "        <input type='text' class='form-control' id='reference' name='reference'>";
    echo "      </div>";

// Supply From and Manufacturer
echo " <div class='col-md-6 mb-3'>";
    echo " <label for='supply_from' class='form-label'>Supply From</label>";
    echo " <input type='text' class='form-control' id='supply_from' name='supply_from'>";
    echo " </div>";
echo " <div class='col-md-6 mb-3'>";
    echo " <label for='manufacturer' class='form-label'>Manufacturer</label>";
    echo " <input type='text' class='form-control' id='manufacturer' name='manufacturer'>";
    echo " </div>";

// Board Type and Installation Date
echo " <div class='col-md-6 mb-3'>";
    echo " <label for='board_type' class='form-label'>Board Type</label>";
    echo " <input type='text' class='form-control' id='board_type' name='board_type'>";
    echo " </div>";
echo " <div class='col-md-6 mb-3'>";
    echo " <label for='installation_date' class='form-label'>Installation Date</label>";
    echo " <input type='date' class='form-control' id='installation_date' name='installation_date'>";
    echo " </div>";

// Confirmed: Polarity and Phase Sequence
echo " <div class='col-md-6 mb-3'>";
    echo " <label class='form-label'>Confirmed</label><br>";
    echo " <div class='form-check form-check-inline'>";
        echo " <input type='checkbox' class='form-check-input' id='polarity_confirmed' name='polarity_confirmed'>";
        echo " <label for='polarity_confirmed' class='form-check-label'>Polarity Confirmed</label>";
        echo " </div>";
    echo " <div class='form-check form-check-inline'>";
        echo " <input type='checkbox' class='form-check-input' id='phase_sequence_confirmed' name='phase_sequence_confirmed'>";
        echo " <label for='phase_sequence_confirmed' class='form-check-label'>Phase Sequence Confirmed</label>";
        echo " </div>";
    echo " </div>"; // End Confirmed section

echo " </div>"; // End row
echo " </div>"; // End card-body
echo "</div>"; // End card for General Board Details

/* =======================================================
Section: Surge Protection Details (wrapped in a card)
======================================================= */
echo "<div class='card mb-4 col-12 col-md-4'>";
    echo " <div class='card-header bg-primary text-light'>Surge Protection Details</div>";
    echo " <div class='card-body'>";
        echo " <div class='row'>";

            echo ' <div class="mb-3">
                <label for="surge_protection_type" class="form-label">Surge Protection Type</label>
                <div>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="surge_protection_type" id="surge_protection_type_1" value="1" required>
                        <label class="form-check-label" for="surge_protection_type_1">Type 1</label>
                    </div>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="surge_protection_type" id="surge_protection_type_2" value="2">
                        <label class="form-check-label" for="surge_protection_type_2">Type 2</label>
                    </div>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="surge_protection_type" id="surge_protection_type_3" value="3">
                        <label class="form-check-label" for="surge_protection_type_3">Type 3</label>
                    </div>
                </div>
            </div>';

            // Part No field
            echo " <div class='col-md-4 mb-3'>";
                echo " <label for='surge_protection_part_no' class='form-label'>Part No</label>";
                echo " <input type='text' class='form-control' id='surge_protection_part_no' name='surge_protection_part_no'>";
                echo " </div>";

            // Functional checkbox
            echo " <div class='col-md-4 mb-3'>";
                echo " <label for='surge_protection_functional' class='form-label'>Functional</label>";
                echo " <div class='form-check'>";
                    echo " <input type='checkbox' class='form-check-input' id='surge_protection_functional' name='surge_protection_functional'>";
                    echo " </div>";
                echo " </div>";

            // Imax field
            echo " <div class='col-md-4 mb-3'>";
                echo " <label for='surge_protection_imax' class='form-label'>Imax (kA)</label>";
                echo " <input type='number' step='0.01' class='form-control' id='surge_protection_imax' name='surge_protection_imax'>";
                echo " </div>";

            echo " </div>"; // End row
        echo " </div>"; // End card-body
    echo "</div>"; // End card for Surge Protection Details

/* =======================================================
Section: Details of Overcurrent Protective Devices (wrapped in a card)
======================================================= */
echo "<div class='card mb-4 col-12 col-md-6'>";
    echo " <div class='card-header bg-primary text-light'>Details of Overcurrent Protective Devices</div>";
    echo " <div class='card-body'>";
        echo " <div class='row'>";

            echo " <div class='col-md-4 mb-3'>";
                echo " <label for='bs_type' class='form-label'>Type BS(EN)</label>";
                echo " <input type='text' class='form-control' id='bs_type' name='bs_type'>";
                echo " </div>";
            echo " <div class='col-md-4 mb-3'>";
                echo " <label for='rating' class='form-label'>Rating (A)</label>";
                echo " <input type='number' class='form-control' id='rating' name='rating'>";
                echo " </div>";
            echo " <div class='col-md-4 mb-3'>";
                echo " <label for='poles' class='form-label'>No. of Poles</label>";
                echo " <input type='number' class='form-control' id='poles' name='poles'>";
                echo " </div>";
            echo " <div class='col-md-6 mb-3'>";
                echo " <label for='mccb_type' class='form-label'>MCCB Type</label>";
                echo " <input type='text' class='form-control' id='mccb_type' name='mccb_type'>";
                echo " </div>";
            echo " <div class='col-md-6 mb-3'>";
                echo " <label for='associated_rcd' class='form-label'>Associated RCD</label>";
                echo " <input type='text' class='form-control' id='associated_rcd' name='associated_rcd'>";
                echo " </div>";

            // Additional fields
            echo " <div class='col-md-4 mb-3'>";
                echo " <label for='trip_current' class='form-label'>Trip Current (mA)</label>";
                echo " <input type='number' class='form-control' id='trip_current' name='trip_current'>";
                echo " </div>";
            echo " <div class='col-md-4 mb-3'>";
                echo " <label for='trip_time_1x' class='form-label'>Trip Time 1x (ms)</label>";
                echo " <input type='text' class='form-control' id='trip_time_1x' name='trip_time_1x'>";
                echo " </div>";

            echo " </div>"; // End row
        echo " </div>"; // End card-body
    echo "</div>"; // End card for Details of Overcurrent Protective Devices

/* =======================================================
Section: Characteristics of Distribution Board (wrapped in a card)
======================================================= */
echo "<div class='card mb-4 col-12 col-md-6'>";
    echo " <div class='card-header bg-primary text-light'>Characteristics of Distribution Board</div>";
    echo " <div class='card-body'>";
        echo " <div class='row'>";

            echo " <div class='col-md-4 mb-3'>";
                echo " <label for='zdb' class='form-label'>Zdb (Ω)</label>";
                echo " <input type='number' step='0.01' class='form-control' id='zdb' name='zdb'>";
                echo " </div>";
            echo " <div class='col-md-4 mb-3'>";
                echo " <label for='pfc_pscc' class='form-label'>PFC/PSCC (kA)</label>";
                echo " <input type='number' step='0.01' class='form-control' id='pfc_pscc' name='pfc_pscc'>";
                echo " </div>";
            echo " <div class='col-md-4 mb-3'>";
                echo " <label for='voltage' class='form-label'>Voltage (V)</label>";
                echo " <input type='number' class='form-control' id='voltage' name='voltage'>";
                echo " </div>";

            echo " </div>"; // End row
        echo " </div>"; // End card-body
    echo "</div>"; // End card for Characteristics of Distribution Board

// Submit Button
echo "<button id='btn_create' type='button' onclick='submitDefineBoardForm()' class='btn btn-info my-4 hidden'>Define Distribution Board</button>";
echo "</div>";
echo "</form>";
echo "</div>";
}


?>

<script>
function submitDefineBoardForm() {
    const form = document.getElementById('defineBoardForm');
    const formData = new FormData(form);

    fetch(ROOT_URL + '/includes/elec/add_distro.php', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status} - ${response.statusText}`);
            }
            return response.text(); // Parse as text to handle both JSON and plain text
        })
        .then(responseText => {
            try {
                const data = JSON.parse(responseText); // Try to parse as JSON
                if (data.success) {
                    window.location.href = `index.php?t=includes/master&p=elec.php&view=elec_client&clientnumber=${data.clientnumber}&action=manage_parts`;
                } else {
                    alert(data.message || 'Error creating the distribution board. Please try again.');
                }
            } catch (e) {
                // If parsing fails, show raw output for debugging
                console.error('Non-JSON response received:', responseText);
                alert('Unexpected server response. Check the console for details.');
            }
        })
        .catch(error => {
            console.error('Error during fetch:', error.message || error);
            alert('An unexpected error occurred. Please check the console for details.');
        });
}

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('navBox').innerHTML =
        '<li class="breadcrumb-item"><a href="index.php?t=includes/master&p=client.php&view=list">Clients</a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li>' +
        '<li class="breadcrumb-item"><a href="index.php?t=includes/master&p=elec.php&clientnumber=<?= $_REQUEST['clientnumber']?>&view=elec_client"><?= getClientName( $_REQUEST['clientnumber'])?></a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li>' +
        '<li class="breadcrumb-item active">New Board</li>'

    document.getElementById('footerControls').innerHTML = '<button class="btn btn-secondary" onclick="triggerAction(\'btn_create\')">Create Board</button>';

});
</script>
<?php ob_end_flush(); // End output buffering and flush output??>