<?php
// elec_list_circuit.php

// 1) Parse incoming data
$d = explode("|", $_REQUEST['data']);
if (!isset($d[0])) {
    die("Error: Board ID is missing.");
}
$board_id = intval($d[0]);

// 2) Fetch board details including circuit_mode
function get_board_details($board_id) {
    global $con;
    $sql = "
      SELECT 
        b.board_name,
        b.circuit_mode,
        CONCAT(l.locname,' [ ',l.postcode,' ]') AS location_name,
        (
          SELECT COUNT(*) 
          FROM elec_circuit 
          WHERE board_id = ?
        ) AS existing_circuits
      FROM elec_board b
      LEFT JOIN locations l ON b.locnumber = l.locnumber
      WHERE b.board_id = ?";
    $stmt = $con->prepare($sql);
    $stmt->bind_param("ii", $board_id, $board_id);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $row ?: [
      'board_name'        => 'Unknown',
      'circuit_mode'      => 'LV',
      'location_name'     => 'Unknown',
      'existing_circuits' => 0
    ];
}

$board = get_board_details($board_id);
?>
<div class="row mb-2">
    <div class="col-12">
        <button class="btn btn-secondary btn-sm float-end" onclick="newCircuit()">
            <i class="fad fa-plus"></i> New Circuit
        </button>
    </div>
</div>

<div class="container-fluid mt-3">
    <h5>
        Circuits for Board: <?= htmlspecialchars($board['board_name']) ?>
        <small class="text-muted">(Board Type: <?= $board['circuit_mode']==='LV' ? '3 Phase' : 'Single Phase' ?>)</small>
    </h5>
    <table id="circuitsTable" class="table table-striped table-bordered table-sm" style="width:100%">
        <thead>
            <tr>
                <th width="5%" class="text-center">Circuit No</th>
                <th>Circuit Descriptions</th>
                <th width="10%">Actions</th>
            </tr>
        </thead>
    </table>
</div>

<script>
// expose the board’s layout mode to JS
const BOARD_MODE = '<?= $board['circuit_mode'] ?>';

document.addEventListener("DOMContentLoaded", () => {
    console.log("� Initializing circuits table for board_id=<?= $board_id ?>");
    $('#circuitsTable').DataTable({
        ajax: {
            url: `${ROOT_URL}/includes/elec/fetch_board_circuits.php`,
            type: 'POST',
            data: {
                board_id: '<?= $board_id ?>',
                tenant: TENANT_URL
            },
            dataSrc: function(json) {
                console.log("� fetch_board_circuits returned:", json);
                if (json.success) {
                    return json.circuits;
                } else {
                    showResponse('danger', 'Failed to load circuits.');
                    return [];
                }
            }
        },
        columns: [{
                data: 'circuit_number',
                title: 'Circuit No'
            },
            {
                data: 'circuit_description',
                title: 'Circuit Descriptions',
                orderable: false,
                render: html => html
            },
            {
                data: 'circuit_id',
                title: 'Actions',
                orderable: false,
                render: id => `
          <button class="btn btn-sm btn-danger float-end" onclick="confirmRemove(${id})">
            <i class="fad fa-trash"></i> Delete
          </button>
          <button class="btn btn-sm btn-secondary float-end me-4" onclick="editCircuit(${id})">
            <i class="fad fa-pencil"></i> Edit
          </button>`
            }
        ],
        responsive: true,
        order: [
            [0, 'asc']
        ]
    });
});

// Navigation helpers
function editCircuit(circuitId) {
    const data = '<?= $_REQUEST['data'] ?>';
    window.location.href =
        `index.php?t=includes/master&p=elec.php&view=elec_edit_circuit` +
        `&circuit_id=${circuitId}&data=${data}`;
}

function newCircuit() {
    const data = encodeURIComponent('<?= $_REQUEST['data'] ?>');
    window.location.href =
        `index.php?t=includes/master&p=elec.php&view=elec_new_circuit&data=${data}`;
}

function confirmRemove(circuitId) {
    const body = '<p>Are you sure you wish to remove this circuit?</p>';
    loadModalContent(
        body,
        "popupBox", "modal-md", 1060, "true",
        "Remove Circuit", "cancelConfirm",
        () => deleteCircuit(circuitId)
    );
}

function deleteCircuit(circuitId) {
    fetch(`${ROOT_URL}/includes/elec/elec_delete_circuit.php`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `circuit_id=${circuitId}&tenant=${TENANT_URL}`
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                showResponse('success', 'Circuit deleted successfully.');
                $('#circuitsTable').DataTable().ajax.reload();
                killModal('popupBox');
            } else {
                showResponse('danger', data.message);
            }
        })
        .catch(err => {
            console.error(err);
            showResponse('danger', 'An unexpected error occurred.');
        });
}

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


})
</script>