<?php
// elec_new_circuit.php

// Parse incoming data: 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] ?? 0);
$locnumber    = intval($d[2] ?? 0);

/**
 * Fetch board details, including our new 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',
      'location_name'    => 'Unknown',
      'existing_circuits'=> 0,
      'circuit_mode'     => 'LV'
    ];
}

/**
 * Determine the next base circuit number by looking at the JSON parts array.
 */
function get_next_circuit_no($board_id) {
    global $con;
    $sql = "
      SELECT MAX(
        CAST(JSON_UNQUOTE(JSON_EXTRACT(parts, '$[0].circuit_no')) AS UNSIGNED)
      ) AS max_base
      FROM elec_circuit
      WHERE board_id = ?";
    $stmt = $con->prepare($sql);
    $stmt->bind_param("i", $board_id);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    return isset($row['max_base']) ? intval($row['max_base']) + 1 : 1;
}

$board_details   = get_board_details($board_id);
$next_circuit_no = get_next_circuit_no($board_id);
$mode            = $board_details['circuit_mode']; // "LV" or "SwitchBoard"
$spurs           = ['L1','L2','L3'];


?>
<style>
.is-invalid {
    border: 1px solid red;
    background-color: #ffeeee;
}
</style>

<div class="note note-secondary mb-3">
    <strong>Define a new circuit (<?= $mode==='LV' ? '3 Phase' : 'Single Phase' ?>):</strong>
    <?= $mode==='LV'
      ? 'Only the “Circuit Description” per section is required.'
      : 'Fill out the single circuit description and details.'
  ?>
</div>

<div class="container-fluid mt-3">
    <div class="row">
        <div class="col-md-9 order-2 order-md-1">
            <form id="newCircuitForm">
                <input type="hidden" name="tenant" value="<?= TENANT_URL ?>">
                <input type="hidden" name="board_id" value="<?= $board_id ?>">
                <input type="hidden" name="clientnumber" value="<?= $clientnumber ?>">
                <input type="hidden" name="locnumber" value="<?= $locnumber ?>">
                <input type="hidden" name="base_circuit_no"
                       value="<?= $next_circuit_no ?>">
                <input type="hidden" name="parts" id="partsJson">
                <input type="hidden" id="circuitMode" name="circuit_mode" value="<?= htmlspecialchars($board_details['circuit_mode']) ?>">

                <?php if ($mode === 'LV'): ?>
                <?php foreach ($spurs as $i => $spur): ?>
                <div class="card mb-3">
                    <div class="card-header d-flex justify-contentboard_detailsn align-items-center p-0 ps-2">
                        <strong>Circuit <?= $next_circuit_no . $spur ?></strong>
                        <button type="button" class="btn btn-link p-0 text-light"
                                onclick="toggleCard('spur<?= $i ?>')">&#9660;</button>
                    </div>
                    <div class="card-body spur-body <?= $spur!=='L1'?'d-none':'' ?>"
                         id="spur<?= $i ?>">
                        <input type="hidden" class="spur-label" value="<?= $spur ?>">

                        <!-- Description -->
                        <div class="mb-3">
                            <label class="form-label">Description (<?= $spur ?>)</label>
                            <input type="text" class="form-control spur-desc" placeholder="Required" required>
                        </div>

                        <!-- Conductor Details -->
                        <h6 class="text-primary">Conductor Details</h6>
                        <div class="row">
                            <div class="col-md-3 mb-3">
                                <label class="form-label">Cable Type</label>
                                <input type="text" class="form-control spur-cable" placeholder="-">
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="form-label">Reference Method</label>
                                <input type="text" class="form-control spur-ref" placeholder="-">
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="form-label">Live (mm²)</label>
                                <input type="number" step="0.01" class="form-control spur-live" placeholder="-">
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="form-label">CPC (mm²)</label>
                                <input type="number" step="0.01" class="form-control spur-cpc" placeholder="-">
                            </div>
                        </div>

                        <!-- Protection Details -->
                        <h6 class="text-primary">Protection Details</h6>
                        <div class="row">
                            <div class="col-md-3 mb-3">
                                <label class="form-label">BS Type</label>
                                <input type="text" class="form-control spur-bs" placeholder="-">
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="form-label">Rating (A)</label>
                                <input type="number" class="form-control spur-rating" placeholder="-">
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="form-label">Breaking Cap (kA)</label>
                                <input type="number" step="0.01" class="form-control spur-bkcap" placeholder="-">
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="form-label">RCD Trip (mA)</label>
                                <input type="number" class="form-control spur-rcdi" placeholder="-">
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="form-label">RCD Type</label>
                                <input type="text" class="form-control spur-rcdt" placeholder="-">
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="form-label">Max Zs (Ω)</label>
                                <input type="number" step="0.01" class="form-control spur-zs" placeholder="-">
                            </div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>

                <?php else: /* single-entry */ ?>
                <div class="card mb-3">
                    <div class="card-header">
                        <strong>Circuit <?= $next_circuit_no ?></strong>
                    </div>
                    <div class="card-body" id="singleCircuit">
                        <input type="hidden" class="spur-label" value="">

                        <!-- Description -->
                        <div class="mb-3">
                            <label class="form-label">Description</label>
                            <input type="text" class="form-control spur-desc" placeholder="Required" required>
                        </div>

                        <!-- Conductor Details -->
                        <h6 class="text-primary">Conductor Details</h6>
                        <div class="row">
                            <div class="col-md-3 mb-3">
                                <label class="form-label">Cable Type</label>
                                <input type="text" class="form-control spur-cable" placeholder="-">
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="form-label">Reference Method</label>
                                <input type="text" class="form-control spur-ref" placeholder="-">
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="form-label">Live (mm²)</label>
                                <input type="number" step="0.01" class="form-control spur-live" placeholder="-">
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="form-label">CPC (mm²)</label>
                                <input type="number" step="0.01" class="form-control spur-cpc" placeholder="-">
                            </div>
                        </div>

                        <!-- Protection Details -->
                        <h6 class="text-primary">Protection Details</h6>
                        <div class="row">
                            <div class="col-md-3 mb-3">
                                <label class="form-label">BS Type</label>
                                <input type="text" class="form-control spur-bs" placeholder="-">
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="form-label">Rating (A)</label>
                                <input type="number" class="form-control spur-rating" placeholder="-">
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="form-label">Breaking Cap (kA)</label>
                                <input type="number" step="0.01" class="form-control spur-bkcap" placeholder="-">
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="form-label">RCD Trip (mA)</label>
                                <input type="number" class="form-control spur-rcdi" placeholder="-">
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="form-label">RCD Type</label>
                                <input type="text" class="form-control spur-rcdt" placeholder="-">
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="form-label">Max Zs (Ω)</label>
                                <input type="number" step="0.01" class="form-control spur-zs" placeholder="-">
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <button type="button" id="btn_create" class="btn btn-info mt-4 hidden"
                        onclick="submitCircuitForm()">
                    Save Circuit
                </button>
            </form>
        </div>

        <div class="col-md-3 order-1 order-md-2 mb-4">
            <div class="card">
                <div class="card-header">Board Information</div>
                <div class="card-body">
                    <p><strong>Name:</strong> <?= htmlspecialchars($board_details['board_name']) ?></p>
                    <p><strong>Location:</strong> <?= htmlspecialchars($board_details['location_name']) ?></p>
                    <p><strong>Existing Circuits:</strong> <?= $board_details['existing_circuits'] ?></p>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function toggleCard(id) {
    document.getElementById(id).classList.toggle('d-none');
}

function submitCircuitForm() {
    const mode = document.getElementById('circuitMode').value;
    const bodies = mode === 'LV' ?
        document.querySelectorAll('.spur-body') : [document.getElementById('singleCircuit')];
    const parts = [];
    let valid = true;

    bodies.forEach(body => {
        const label = body.querySelector('.spur-label').value;
        const desc = body.querySelector('.spur-desc').value.trim();
        if (!desc) {
            body.querySelector('.spur-desc').classList.add('is-invalid');
            valid = false;
            return;
        }
        body.querySelector('.spur-desc').classList.remove('is-invalid');

        parts.push({
            label,
            circuit_no: document.querySelector('input[name="base_circuit_no"]').value + label,
            circuit_description: desc,
            cable_type: body.querySelector('.spur-cable').value.trim() || '-',
            reference_method: body.querySelector('.spur-ref').value.trim() || '-',
            number_size_live: parseFloat(body.querySelector('.spur-live').value) || 0,
            number_size_cpc: parseFloat(body.querySelector('.spur-cpc').value) || 0,
            bs_type: body.querySelector('.spur-bs').value.trim() || '-',
            rating: parseInt(body.querySelector('.spur-rating').value) || 0,
            breaking_capacity: parseFloat(body.querySelector('.spur-bkcap').value) || 0,
            rcd_tripping_current: parseInt(body.querySelector('.spur-rcdi').value) || 0,
            rcd_type: body.querySelector('.spur-rcdt').value.trim() || '-',
            max_allowed_zs: parseFloat(body.querySelector('.spur-zs').value) || 0
        });
    });

    if (!valid) {
        showResponse("warning", "Please fill out all required descriptions.");
        return;
    }

    document.getElementById('partsJson').value = JSON.stringify(parts);

    fetch(
            ROOT_URL + '/includes/elec/elec_add_circuit.php', {
                method: 'POST',
                body: new FormData(document.getElementById('newCircuitForm'))
            }
        )
        .then(r => r.json())
        .then(json => {
            if (json.success) {
                showResponse('success', 'Circuit added successfully!');
                window.location.href =
                    'index.php?t=includes/master&p=elec.php&view=elec_list_circuit&data=<?= urlencode($_REQUEST['data']) ?>';
            } else {
                showResponse('danger', json.message);
            }
        })
        .catch(err => {
            console.error(err);
            showResponse('danger', 'Unexpected error');
        });
}

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"><a href="index.php?t=includes/master&p=elec.php&view=elec_list_circuit&data=<?=$_REQUEST['data']?>">Circuits</a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li>' +
        '<li class="breadcrumb-item active">Edit Circuit</li>'

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