<?php
// elec_edit_circuit.php


// 2) Parse inputs
$circuit_id = isset($_REQUEST['circuit_id']) ? intval($_REQUEST['circuit_id']) : 0;
if (!$circuit_id) {
    die("<div class='alert alert-danger'>Missing circuit_id.</div>");
}
list($board_id,$clientnumber,$locnumber) = explode('|', $_REQUEST['data']);

// 3) Fetch circuit + board mode
$stmt = $con->prepare("
    SELECT c.base_circuit_no, c.parts, b.circuit_mode
      FROM elec_circuit c
      JOIN elec_board   b ON b.board_id = c.board_id
     WHERE c.circuit_id = ?
");
$stmt->bind_param("i",$circuit_id);
$stmt->execute();
$rec = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$rec) {
    die("<div class='alert alert-danger'>Circuit not found.</div>");
}

$baseNo    = $rec['base_circuit_no'];
$parts     = json_decode($rec['parts'], true) ?: [];
$mode      = $rec['circuit_mode']; // "LV" or "SwitchBoard"
$spurs     = ['L1','L2','L3'];
?>
<div class="container-fluid">
    <h4>Edit Circuit <?= htmlspecialchars($baseNo) ?></h4>
    <form id="editCircuitForm">
        <input type="hidden" name="tenant" value="<?= TENANT_URL ?>">
        <input type="hidden" name="circuit_id" value="<?= $circuit_id ?>">
        <input type="hidden" name="parts" id="partsJson">
        <input type="hidden" name="base_circuit_no" value="<?= $baseNo ?>">

        <div class="form-group mb-3">
            <label>Display Mode</label>
            <select id="circuitMode" class="form-control">
                <option value="LV" <?= $mode==='LV'?'selected':'' ?>>LV (3-spur)</option>
                <option value="SwitchBoard" <?= $mode==='SwitchBoard'?'selected':'' ?>>SwitchBoard (single entry)</option>
            </select>
        </div>

        <!-- inside your form, replace spurContainer with: -->
        <div id="spurContainer">
            <?php foreach($spurs as $spur): ?>
            <div class="card mb-3 spur-card" data-spur="<?= $spur ?>">
                <div class="card-header"><strong><?= $baseNo . $spur ?></strong></div>
                <div class="card-body">
                    <!-- Description -->
                    <div class="mb-3">
                        <label class="form-label">Description (<?= $spur ?>)</label>
                        <input type="text" class="form-control spur-desc">
                    </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">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Reference Method</label>
                            <input type="text" class="form-control spur-ref">
                        </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">
                        </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">
                        </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">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Rating (A)</label>
                            <input type="number" class="form-control spur-rating">
                        </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">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">RCD Trip (mA)</label>
                            <input type="number" class="form-control spur-rcdi">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">RCD Type</label>
                            <input type="text" class="form-control spur-rcdt">
                        </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">
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

        <!-- and replace singleContainer with: -->
        <div id="singleContainer" class="d-none">
            <div class="card mb-3">
                <div class="card-header"><strong><?= $baseNo ?></strong></div>
                <div class="card-body">

                    <!-- Description -->
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <input type="text" class="form-control single-desc">
                    </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 single-cable">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Reference Method</label>
                            <input type="text" class="form-control single-ref">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Live (mm²)</label>
                            <input type="number" step="0.01" class="form-control single-live">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">CPC (mm²)</label>
                            <input type="number" step="0.01" class="form-control single-cpc">
                        </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 single-bs">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Rating (A)</label>
                            <input type="number" class="form-control single-rating">
                        </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 single-bkcap">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">RCD Trip (mA)</label>
                            <input type="number" class="form-control single-rcdi">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">RCD Type</label>
                            <input type="text" class="form-control single-rcdt">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Max Zs (Ω)</label>
                            <input type="number" step="0.01" class="form-control single-zs">
                        </div>
                    </div>

                </div>
            </div>
        </div>


        <div id="singleContainer" class="d-none">
            <div class="card mb-3">
                <div class="card-header"><strong><?= $baseNo ?></strong></div>
                <div class="card-body">
                    <div class="mb-2">
                        <label>Description</label>
                        <input type="text" class="form-control single-desc">
                    </div>
                    <div class="row">
                        <div class="col"><input type="text" placeholder="Cable Type" class="form-control single-cable"></div>
                        <div class="col"><input type="text" placeholder="Reference Method" class="form-control single-ref"></div>
                        <div class="col"><input type="number" step="0.01" placeholder="Live (mm²)" class="form-control single-live"></div>
                        <div class="col"><input type="number" step="0.01" placeholder="CPC (mm²)" class="form-control single-cpc"></div>
                    </div>
                    <hr>
                    <div class="row">
                        <div class="col"><input type="text" placeholder="BS Type" class="form-control single-bs"></div>
                        <div class="col"><input type="number" placeholder="Rating (A)" class="form-control single-rating"></div>
                        <div class="col"><input type="number" step="0.01" placeholder="Bk Cap (kA)" class="form-control single-bkcap"></div>
                        <div class="col"><input type="number" placeholder="RCD Trip (mA)" class="form-control single-rcdi"></div>
                        <div class="col"><input type="text" placeholder="RCD Type" class="form-control single-rcdt"></div>
                        <div class="col"><input type="number" step="0.01" placeholder="Max Zs (Ω)" class="form-control single-zs"></div>
                    </div>
                </div>
            </div>
        </div>

        <button id="btn_update" type="button" class="btn btn-primary hidden" onclick="submitEditCircuit()">Save Changes</button>
    </form>
</div>

<script>
// inject PHP data into JS
const boardMode = "<?= $mode ?>";
const existingParts = <?= json_encode($parts) ?>;

document.addEventListener('DOMContentLoaded', () => {
    const modeSelect = document.getElementById('circuitMode');
    const spurCt = document.getElementById('spurContainer');
    const singleCt = document.getElementById('singleContainer');

    // show/hide on mode
    function refreshMode(m) {
        if (m === 'LV') {
            spurCt.classList.remove('d-none');
            singleCt.classList.add('d-none');
        } else {
            spurCt.classList.add('d-none');
            singleCt.classList.remove('d-none');
        }
    }
    modeSelect.value = boardMode;
    refreshMode(boardMode);
    modeSelect.addEventListener('change', e => refreshMode(e.target.value));

    // pre-fill existingParts
    if (boardMode === 'LV') {
        document.querySelectorAll('.spur-card').forEach(card => {
            const lab = card.dataset.spur;
            const part = existingParts.find(p => p.label === lab) || {};
            card.querySelector('.spur-desc').value = part.circuit_description || '';
            card.querySelector('.spur-cable').value = part.cable_type || '';
            card.querySelector('.spur-ref').value = part.reference_method || '';
            card.querySelector('.spur-live').value = part.number_size_live || '';
            card.querySelector('.spur-cpc').value = part.number_size_cpc || '';
            card.querySelector('.spur-bs').value = part.bs_type || '';
            card.querySelector('.spur-rating').value = part.rating || '';
            card.querySelector('.spur-bkcap').value = part.breaking_capacity || '';
            card.querySelector('.spur-rcdi').value = part.rcd_tripping_current || '';
            card.querySelector('.spur-rcdt').value = part.rcd_type || '';
            card.querySelector('.spur-zs').value = part.max_allowed_zs || '';
        });
    } else {
        const p = existingParts[0] || {};
        document.querySelector('.single-desc').value = p.circuit_description || '';
        document.querySelector('.single-cable').value = p.cable_type || '';
        document.querySelector('.single-ref').value = p.reference_method || '';
        document.querySelector('.single-live').value = p.number_size_live || '';
        document.querySelector('.single-cpc').value = p.number_size_cpc || '';
        document.querySelector('.single-bs').value = p.bs_type || '';
        document.querySelector('.single-rating').value = p.rating || '';
        document.querySelector('.single-bkcap').value = p.breaking_capacity || '';
        document.querySelector('.single-rcdi').value = p.rcd_tripping_current || '';
        document.querySelector('.single-rcdt').value = p.rcd_type || '';
        document.querySelector('.single-zs').value = p.max_allowed_zs || '';
    }
});

function submitEditCircuit() {
    let parts = [];
    if (document.getElementById('circuitMode').value === 'LV') {
        document.querySelectorAll('.spur-card').forEach(card => {
            parts.push({
                label: card.dataset.spur,
                circuit_no: document.querySelector('input[name="base_circuit_no"]').value + card.dataset.spur,
                circuit_description: card.querySelector('.spur-desc').value.trim(),
                cable_type: card.querySelector('.spur-cable').value.trim() || '-',
                reference_method: card.querySelector('.spur-ref').value.trim() || '-',
                number_size_live: parseFloat(card.querySelector('.spur-live').value) || 0,
                number_size_cpc: parseFloat(card.querySelector('.spur-cpc').value) || 0,
                bs_type: card.querySelector('.spur-bs').value.trim() || '-',
                rating: parseInt(card.querySelector('.spur-rating').value) || 0,
                breaking_capacity: parseFloat(card.querySelector('.spur-bkcap').value) || 0,
                rcd_tripping_current: parseInt(card.querySelector('.spur-rcdi').value) || 0,
                rcd_type: card.querySelector('.spur-rcdt').value.trim() || '-',
                max_allowed_zs: parseFloat(card.querySelector('.spur-zs').value) || 0
            });
        });
    } else {
        const c = document.querySelector('.single-desc').closest('.card-body');
        parts.push({
            label: '',
            circuit_no: document.querySelector('input[name="base_circuit_no"]').value,
            circuit_description: c.querySelector('.single-desc').value.trim(),
            cable_type: c.querySelector('.single-cable').value.trim() || '-',
            reference_method: c.querySelector('.single-ref').value.trim() || '-',
            number_size_live: parseFloat(c.querySelector('.single-live').value) || 0,
            number_size_cpc: parseFloat(c.querySelector('.single-cpc').value) || 0,
            bs_type: c.querySelector('.single-bs').value.trim() || '-',
            rating: parseInt(c.querySelector('.single-rating').value) || 0,
            breaking_capacity: parseFloat(c.querySelector('.single-bkcap').value) || 0,
            rcd_tripping_current: parseInt(c.querySelector('.single-rcdi').value) || 0,
            rcd_type: c.querySelector('.single-rcdt').value.trim() || '-',
            max_allowed_zs: parseFloat(c.querySelector('.single-zs').value) || 0
        });
    }

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

    fetch(ROOT_URL + '/includes/elec/elec_update_circuit.php', {
            method: 'POST',
            body: new FormData(document.getElementById('editCircuitForm'))
        })
        .then(r => r.json())
        .then(d => {
            if (d.success) {
                showResponse('success', 'Circuit updated');
                window.location.href = `index.php?t=includes/master&p=elec.php&view=elec_list_circuit&data=<?= $_REQUEST['data'] ?>`;
            } else {
                showResponse('danger', d.message);
            }
        })
        .catch(e => {
            console.error(e);
            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_update\')">Update Circuit</button>';
})
</script>