<?php
ob_start();
require_once(ROOT_URL . '/includes/elec/elec_distro_functions.php');
require_once(ROOT_URL . '/includes/master/form_functions.php');

// Expecting data to be passed as a pipe‑delimited string: board_id|clientnumber|locnumber
$d = explode("|", $_REQUEST['data']);
if (!isset($d[0])) {
    die("Error: Board ID is missing.");
}
$board_id = intval($d[0]);
$clientnumber = intval($d[1]);
$locnumber = intval($d[2]);

if (!$board_id) {
    echo "<div class='container'><p>Error: Board ID not specified.</p></div>";
    exit;
}

// Retrieve board details from the database
$board = get_distro_details($board_id);
if (!$board) {
    echo "<div class='container'><p>Error: Distribution Board not found.</p></div>";
    exit;
}

echo "<div class='container-fluid'>";
echo "  <h2 class='my-4'>Edit Distribution Board for " . getClientName($board['clientnumber']) . "</h2>";
echo "  <form id='editBoardForm' method='post'>";
echo "    <input type='hidden' name='edit_board' value='1'>";
echo "    <input type='hidden' name='board_id' value='{$board_id}'>";
echo "    <input type='hidden' name='tenant' value='" . TENANT_URL . "'>";
echo "    <input type='hidden' name='clientnumber' value='{$board['clientnumber']}'>";

// -------------------------------
// Card 1: 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'>";

// Circuit layout
echo "            <div class='col-md-6 mb-3'>";
echo "              <label for='circuit_mode ' class='form-label'>Circuit layout</label>";
echo "              <select name='circuit_mode' id='circuit_mode' class='form-control'>";
echo "                <option value='LV'" . ($board['circuit_mode']==='LV' ? " selected" : "") . ">3 Phase</option>";
echo "                <option value='SwitchBoard'" . ($board['circuit_mode']==='SwitchBoard' ? " selected" : "") . ">Single Phase</option>";
echo "              </select>";
echo "            </div>";
// Board Name
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' value='" . htmlspecialchars($board['board_name']) . "' required>";
echo "            </div>";
// Location (using getSites function)
echo "            <div class='col-md-6 mb-3'>";
echo "              <label for='siteList' class='form-label'>Location</label>";
echo                    getSites2($clientnumber, $board['locnumber']);
echo "            </div>";
// Reference
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' value='" . htmlspecialchars($board['reference']) . "'>";
echo "            </div>";
// Supply From
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' value='" . htmlspecialchars($board['supply_from']) . "'>";
echo "            </div>";
// Manufacturer
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' value='" . htmlspecialchars($board['manufacturer']) . "'>";
echo "            </div>";
// Board Type
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' value='" . htmlspecialchars($board['board_type']) . "'>";
echo "            </div>";
// Installation Date
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' value='" . htmlspecialchars($board['installation_date']) . "'>";
echo "            </div>";
// Confirmed checkboxes
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' " . ($board['polarity_confirmed'] ? "checked" : "") . ">";
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' " . ($board['phase_sequence_confirmed'] ? "checked" : "") . ">";
echo "                <label for='phase_sequence_confirmed' class='form-check-label'>Phase Sequence Confirmed</label>";
echo "              </div>";
echo "            </div>"; // End Confirmed checkboxes
echo "          </div>"; // End row inside card-body
echo "        </div>"; // End card-body
echo "      </div>"; // End card for General Board Details

// ----------------------------------
// Card 2: Surge Protection Details
// ----------------------------------
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'>";
// Surge Protection Type radio buttons
echo "            <div class='mb-3'>";
echo "              <label for='surge_protection_type' class='form-label'>Surge Protection Type</label>";
echo "              <div>";
echo "                <div class='form-check form-check-inline'>";
echo "                  <input class='form-check-input' type='radio' name='surge_protection_type' id='surge_protection_type_1' value='1' " . ($board['surge_protection_type'] == 1 ? "checked" : "") . " required>";
echo "                  <label class='form-check-label' for='surge_protection_type_1'>Type 1</label>";
echo "                </div>";
echo "                <div class='form-check form-check-inline'>";
echo "                  <input class='form-check-input' type='radio' name='surge_protection_type' id='surge_protection_type_2' value='2' " . ($board['surge_protection_type'] == 2 ? "checked" : "") . ">";
echo "                  <label class='form-check-label' for='surge_protection_type_2'>Type 2</label>";
echo "                </div>";
echo "                <div class='form-check form-check-inline'>";
echo "                  <input class='form-check-input' type='radio' name='surge_protection_type' id='surge_protection_type_3' value='3' " . ($board['surge_protection_type'] == 3 ? "checked" : "") . ">";
echo "                  <label class='form-check-label' for='surge_protection_type_3'>Type 3</label>";
echo "                </div>";
echo "              </div>";
echo "            </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' value='" . htmlspecialchars($board['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' " . ($board['surge_protection_functional'] ? "checked" : "") . ">";
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' value='" . htmlspecialchars($board['surge_protection_imax']) . "'>";
echo "            </div>";
echo "          </div>"; // End row in card-body
echo "        </div>"; // End card-body
echo "      </div>"; // End card for Surge Protection Details

// ----------------------------------------------------
// Card 3: Details of Overcurrent Protective Devices
// ----------------------------------------------------
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'>";
// BS Type
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' value='" . htmlspecialchars($board['bs_type']) . "'>";
echo "            </div>";
// Rating
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' value='" . htmlspecialchars($board['rating']) . "'>";
echo "            </div>";
// No. of Poles
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' value='" . htmlspecialchars($board['poles']) . "'>";
echo "            </div>";
// MCCB Type
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' value='" . htmlspecialchars($board['mccb_type']) . "'>";
echo "            </div>";
// Associated RCD
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' value='" . htmlspecialchars($board['associated_rcd']) . "'>";
echo "            </div>";
// Trip Current
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' value='" . htmlspecialchars($board['trip_current']) . "'>";
echo "            </div>";
// Trip Time 1x
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' value='" . htmlspecialchars($board['trip_time_1x']) . "'>";
echo "            </div>";
echo "          </div>"; // End row in card-body
echo "        </div>"; // End card-body
echo "      </div>"; // End card for Overcurrent Protective Devices

// -------------------------------------------------
// Card 4: Characteristics of Distribution Board
// -------------------------------------------------
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'>";
// Zdb
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' value='" . htmlspecialchars($board['zdb']) . "'>";
echo "            </div>";
// PFC/PSCC
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' value='" . htmlspecialchars($board['pfc_pscc']) . "'>";
echo "            </div>";
// Voltage
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' value='" . htmlspecialchars($board['voltage']) . "'>";
echo "            </div>";
echo "          </div>"; // End row in card-body
echo "        </div>"; // End card-body
echo "      </div>"; // End card for Characteristics of Distribution Board

echo "    </div>"; // End row for all cards

// Submit Button
echo "    <button id='btn_update' type='button' onclick='submitEditBoardForm()' class='btn btn-info my-4 hidden'>Save Changes</button>";
echo "  </form>";
echo "</div>";

ob_end_flush();
?>
<script>
// JavaScript function to submit the edit form via fetch
function submitEditBoardForm() {
    const form = document.getElementById('editBoardForm');
    const formData = new FormData(form);

    fetch(ROOT_URL + '/includes/elec/update_distro.php', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status} - ${response.statusText}`);
            }
            return response.text();
        })
        .then(responseText => {
            try {
                const data = JSON.parse(responseText);
                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 updating the distribution board. Please try again.');
                }
            } catch (e) {
                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.');
        });
}

// Example breadcrumb and footer setup (if needed)
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=' + <?= $clientnumber ?> + '&view=elec_client">' + '<?= getClientName($clientnumber) ?>' +
        '</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&view=elec_list_circuit&data=' + encodeURIComponent("<?= $_REQUEST['data'] ?>") + '">Board: ' + '<?= htmlspecialchars($board['board_name']) ?>' +
        '</a><i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li>' +
        '<li class="breadcrumb-item active">Edit Board</li>';

    document.getElementById('footerControls').innerHTML = '<button class="btn btn-secondary" onclick="triggerAction(\'btn_update\')">Update Board</button>';
});
</script>