<?php
// inspection_test_results.php

// Display header note with Circuit Index button
echo '<div class="note note-secondary mb-3">'
   . '<strong>Inspection and Test Results</strong>'
   . '<span class="float-end">'
   . '<button id="openSidebarBtn" class="btn btn-info" onclick="openSidebar()">'
   . '<i class="fad fa-list me-1"></i> Circuit Index</button>'
   . '</span>'
   . '</div>';

// Retrieve existing report data
$master_report_id = $_GET['master_report_id'] ?? null;
$board_id         = $_GET['board_id']         ?? null;
$reportData       = [];
if ($master_report_id && $board_id) {
    $sql = "SELECT  circuit_results, 
                observation_data,
                surveyor_id,
                inspection_date FROM elec_report WHERE master_report_id = ? AND board_id = ?";
    $stmt = $con->prepare($sql);
    $stmt->bind_param("si", $master_report_id, $board_id);
    $stmt->execute();
    $reportData = $stmt->get_result()->fetch_assoc();
    $stmt->close();
}
$inspector  = $reportData['surveyor_id']      ?? '';
$insp_date  = $reportData['inspection_date']  ?? '';
// Decode JSON data
$circuitData     = !empty($reportData['circuit_results']) ? json_decode($reportData['circuit_results'], true) : [];
$observationData = !empty($reportData['observation_data']) ? json_decode($reportData['observation_data'], true) : [];

// Fetch circuits JSON parts
$sql = "SELECT circuit_id, base_circuit_no, parts FROM elec_circuit WHERE board_id = ? ORDER BY CAST(base_circuit_no AS UNSIGNED) ASC";
$stmt = $con->prepare($sql);
$stmt->bind_param("i", $board_id);
$stmt->execute();
$result = $stmt->get_result();

// Fetch list of active surveyors
$surveyors = [];
$sSql = "SELECT id, forename, surname FROM surveyor WHERE statuslive=1 ORDER BY forename";
$stmt2 = $con->prepare($sSql);
$stmt2->execute();
$res2 = $stmt2->get_result();
while ($r = $res2->fetch_assoc()) {
    $surveyors[] = $r;
}
$stmt2->close();

// Group circuits by numeric prefix
$groupedCircuits = [];
while ($row = $result->fetch_assoc()) {
    $parts = json_decode($row['parts'], true) ?: [];
    foreach ($parts as $p) {
        $grp = preg_match('/^(\d+)/', $p['circuit_no'], $m) ? $m[1] : '0';
        $groupedCircuits[$grp][] = ['circuit_no'=>$p['circuit_no'],'circuit_description'=>$p['circuit_description']];
    }
}
$stmt->close();
ksort($groupedCircuits);
$allGroups  = array_keys($groupedCircuits);
$totalPages = count($allGroups);
?>
<script>
//const BOARD_ID = <?= json_encode($board_id) ?>;
</script>
<style>
#circuitContainer {
    position: relative;
    overflow: hidden;
}

body {
    overflow-x: hidden;
}

/* Off-canvas sidebar positioned on the right */
.off-canvas-sidebar {
    position: fixed;
    top: 0;
    right: -350px;
    /* Initially hidden offscreen to the right */
    width: 350px;
    height: 100%;
    background: #f8f9fa;
    box-shadow: -2px 0 5px rgba(0, 0, 0, 0.3);
    transition: right 0.3s ease;
    z-index: 1050;
    padding: 1rem;
    overflow-y: auto;
    border-top-left-radius: 10px;
    border-bottom-left-radius: 10px;
}

.off-canvas-sidebar.open {
    right: 0;
    /* Slides in from the right */
}

.sidebar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
}

.close-sidebar {
    background: none;
    border: none;
    font-size: 1.5rem;
    line-height: 1;
    cursor: pointer;
}

.sidebar-list {
    list-style: none;
    padding: 0;
    margin: 0;
}

.sidebar-list li {
    margin-bottom: 0.5rem;
}

.sidebar-list li a {
    color: #007bff;
    text-decoration: none;
}

.sidebar-list li a:hover {
    text-decoration: underline;
}



/* Responsive adjustments for smaller screens */
@media (max-width: 768px) {
    .off-canvas-sidebar {
        width: 80%;
        right: -80%;
    }

    .off-canvas-sidebar.open {
        right: 0;
    }
}
</style>
<!-- Off-canvas Sidebar for Circuit Index (positioned on the right) -->
<div id="offCanvasSidebar" class="off-canvas-sidebar p-0">
    <div class="sidebar-header d-flex justify-content-between align-items-center border-bottom pb-2 ps-2 mb-3 bg-info text-light">
        <h5 class="mb-0">
            <i class="fad fa-bolt me-2"></i> Circuit Index
        </h5>
        <button type="button" class="btn btn-link text-danger" onclick="closeSidebar()">
            <i class="fad fa-window-close fa-2x"></i>
        </button>
    </div>
    <div class="list-group list-group-flush">
        <?php foreach ($groupedCircuits as $group => $circuits): ?>
        <div class="list-group-item">
            <!-- Group Header -->
            <div class="fw-bold">
                <i class="fad fa-bolt me-1"></i> Circuit <?php echo htmlspecialchars($group, ENT_QUOTES, 'UTF-8'); ?>:
            </div>
            <!-- List each circuit part -->
            <div class="ms-3">
                <?php foreach ($circuits as $circuit): 
                    $ends = substr($circuit["circuit_no"], -2);
                    // Determine the background color based on the ending
                    if ($ends === "L1") {
                        $bgColor = "darkred";
                    } elseif ($ends === "L2") {
                        $bgColor = "black";
                    } elseif ($ends === "L3") {
                        $bgColor = "grey";
                    } else {
                        $bgColor = "transparent"; // or any default value
                    }?>
                <div>
                    <a href="#" class="list-group-item list-group-item-action px-3 border-" onclick='selectCircuit("<?= htmlspecialchars($circuit["circuit_no"], ENT_QUOTES) ?>"); return false;'>
                        <strong style="background-color: <?php echo $bgColor; ?>; color: white;" class="ps-1">
                            <?= htmlspecialchars($circuit["circuit_no"], ENT_QUOTES, "UTF-8") ?>:
                        </strong>
                        &nbsp;
                        <?php echo htmlspecialchars($circuit['circuit_description'], ENT_QUOTES, 'UTF-8'); ?>
                    </a>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endforeach; ?>
    </div>



</div>
<form id="circuitInspectionForm" enctype="multipart/form-data">
    <input type="hidden" name="master_report_id" value="<?= htmlspecialchars($master_report_id,ENT_QUOTES) ?>">
    <input type="hidden" name="board_id" value="<?= htmlspecialchars($board_id,ENT_QUOTES) ?>">

    <!-- Circuit Cards -->
    <div id="circuitContainer">
        <?php foreach($allGroups as $idx=>$grp):
      $page = $idx+1;
      $display = $page===1?'block':'none';
      foreach($groupedCircuits[$grp] as $row):
        $cno = $row['circuit_no'];
        $vals = $circuitData[$cno] ?? [];
  ?>

        <div id="circuit-<?= htmlspecialchars($cno, ENT_QUOTES) ?>" class="circuit-card" data-page="<?= $page ?>" style="display: <?= $display ?>;">
            <div class="card mb-3">
                <div class="card-header bg-light">
                    <h5>Circuit <?= htmlspecialchars($cno,ENT_QUOTES) ?>: <?= htmlspecialchars($row['circuit_description'],ENT_QUOTES) ?></h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <!-- Continuity -->
                        <div class="col-lg-3">
                            <h6 class="text-primary">Continuity</h6>
                            <?php foreach(['r1','rn','r2','r1_r2','r2_continuity'] as $f): ?>
                            <div class="mb-2">
                                <label><?= strtoupper(str_replace('_',' ', $f)) ?> (Ω)</label>
                                <input type="text" name="circuit_results[<?= $cno ?>][<?= $f ?>]" class="form-control form-control-sm" value="<?= htmlspecialchars($vals[$f]??'',ENT_QUOTES) ?>" required>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <!-- Insulation -->
                        <div class="col-lg-3">
                            <h6 class="text-primary">Insulation Resistance</h6>
                            <?php foreach(['pp','pe'] as $f): ?>
                            <div class="mb-2">
                                <label><?= strtoupper($f) ?> (MΩ)</label>
                                <input type="text" name="circuit_results[<?= $cno ?>][<?= $f ?>]" class="form-control form-control-sm" value="<?= htmlspecialchars($vals[$f]??'',ENT_QUOTES) ?>" required>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <!-- Polarity & Zs -->
                        <div class="col-lg-3">
                            <h6 class="text-primary">Polarity Confirmed</h6>
                            <div class="form-check mb-2">
                                <input type="checkbox" name="circuit_results[<?= $cno ?>][polarity]" value="1" class="form-check-input" <?= !empty($vals['polarity'])?'checked':'' ?>>
                                <label class="form-check-label">Yes</label>
                            </div>
                            <h6 class="text-primary">Measured Zs (Ω)</h6>
                            <div class="mb-2">
                                <input type="text" name="circuit_results[<?= $cno ?>][zs]" class="form-control form-control-sm" value="<?= htmlspecialchars($vals['zs']??'',ENT_QUOTES) ?>" required>
                            </div>
                            <h6 class="text-primary">Earth Leakage (mA)</h6>
                            <div class="mb-2">
                                <input type="text" name="circuit_results[<?= $cno ?>][earth_leakage]" class="form-control form-control-sm" value="<?= htmlspecialchars($vals['earth_leakage']??'',ENT_QUOTES) ?>" required>
                            </div>
                        </div>
                        <!-- RCD/AFDD -->
                        <div class="col-lg-3">
                            <h6 class="text-primary">RCD Trip Time (ms)</h6>
                            <div class="mb-2">
                                <input type="text" name="circuit_results[<?= $cno ?>][rcd_trip_time]" class="form-control form-control-sm" value="<?= htmlspecialchars($vals['rcd_trip_time']??'',ENT_QUOTES) ?>" required>
                            </div>
                            <?php foreach(['rcd_functional','afdd_functional'] as $f): ?>
                            <div class="form-check mb-2">
                                <input type="checkbox" name="circuit_results[<?= $cno ?>][<?= $f ?>]" value="1" class="form-check-input" <?= !empty($vals[$f])?'checked':'' ?>>
                                <label class="form-check-label"><?= ucfirst(str_replace('_',' ', $f)) ?></label>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; endforeach; ?>
    </div>

    <!-- Observation Panels per Group -->
    <div id="observationsContainer">
        <?php foreach ($allGroups as $idx => $grp):
      $page    = $idx + 1;
      $display = $page === 1 ? 'block' : 'none';
      $rawObs  = $observationData[$grp] ?? [];
      $obsList = is_array($rawObs) && count($rawObs) > 0
               ? $rawObs
               : [['fault_code'=>'C1','text'=>'','fi'=>0]];
  ?>
        <div class="observation-panel" data-group="<?= $grp ?>" data-page="<?= $page ?>"
             style="display: <?= $display ?>; margin-bottom:2rem;">
            <div class="obs-rows">

                <?php foreach ($obsList as $i => $obs): ?>
                <div class="card mb-3 obs-card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <span>Observation #<?= ($i+1) ?></span>
                        <button type="button"
                                class="btn btn-sm btn-danger remove-observation"
                                data-idx="<?= $i ?>">
                            <i class="fad fa-trash-alt"></i>
                        </button>
                    </div>
                    <div class="card-body">
                        <div class="row g-3 mb-2 obs-row">
                            <div class="col-md-2">
                                <label>Fault Code</label>
                                <select name="observations[<?= $grp ?>][<?= $i ?>][fault_code]"
                                        class="form-select form-select-sm">
                                    <option value="C1" <?= $obs['fault_code']==='C1'?'selected':'' ?>>C1</option>
                                    <option value="C2" <?= $obs['fault_code']==='C2'?'selected':'' ?>>C2</option>
                                    <option value="C3" <?= $obs['fault_code']==='C3'?'selected':'' ?>>C3</option>
                                    <option value="FI" <?= $obs['fault_code']==='FI'?'selected':'' ?>>FI</option>
                                </select>
                            </div>
                            <div class="col-md-8">
                                <label>Observations</label>
                                <div class="d-flex">
                                    <textarea id="observations[<?= $grp ?>][<?= $i ?>][text]" name="observations[<?= $grp ?>][<?= $i ?>][text]" class="form-control form-control-sm"
                                              rows="2"><?= htmlspecialchars($obs['text'], ENT_QUOTES) ?></textarea>
                                    <div class="d-flex flex-column">
                                        <button type="button" class="btn btn-secondary mb-1 ms-4" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Clear Field"
                                                onClick="clearbox('observations[<?= $grp ?>][<?= $i ?>][text]')">
                                            <i class="fad fa-eraser"></i>
                                        </button>
                                        <?php if($_SESSION['usertype']=="admins"){ ?>
                                        <button type="button" class="btn btn-info mb-1 ms-4" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="View List"
                                                onClick="autofillElec('formComplete','observations[<?= $grp ?>][<?= $i ?>][text]','elecphrases')">
                                            <i class="fad fa-edit"></i>
                                        </button>
                                        <button type="button" class="btn btn-success mb-1 ms-4" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Save field as new entry"
                                                onClick="savebox('observations[<?= $grp ?>][<?= $i ?>][text]','elecphrases')">
                                            <i class="fad fa-save"></i>
                                        </button>
                                        <?php } else { ?>
                                        <button type="button" class="btn btn-success mb-1 ms-4" onClick="javascript:void(0)"></button>
                                        <button type="button" class="btn btn-info mb-1 ms-4" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="View List"
                                                onClick="autofillElec('formComplete','observations[<?= $grp ?>][<?= $i ?>][text]','elecphrases')">
                                            <i class="fad fa-edit"></i>
                                        </button>
                                        <?php } ?>
                                        <button type="button" class="btn btn-danger btn-info-alt ms-4" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Reset FIeld"
                                                onClick="resetBox('observations[<?= $grp ?>][<?= $i ?>][text]')">
                                            <i class="fad fa-refresh"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-2 text-center form-check">
                                <label>FI Y/N</label><br>
                                <input type="checkbox" name="observations[<?= $grp ?>][<?= $i ?>][fi]"
                                       class="form-check-input" value="1" <?= !empty($obs['fi'])?'checked':'' ?>>
                            </div>
                        </div>
                        <div class="row mb-3 img-row">
                            <div class="col-12">
                                <label>Upload Images</label>
                                <div class="row image-uploads" data-group="<?= $grp ?>" data-obs="<?= $i ?>">
                                    <?php for ($j=1; $j<=6; $j++):
                                    $fn   = "{$master_report_id}_{$board_id}_{$grp}_{$i}_{$j}.jpg";
                                    $path = TENANT_DEFER."/images/report_images/{$fn}";
                                    $src  = "images/report_images/{$fn}?".rand();
                                    ?>
                                    <div class="col-lg-2 col-md-4 col-6 mb-2">
                                        <div class="imup"
                                             data-service="images/elec_save.php"
                                             data-target="<?= $fn ?>"
                                             data-meta-reportid="<?= $master_report_id ?>"
                                             data-meta-boardid="<?= $board_id ?>"
                                             data-meta-group="<?= $grp ?>"
                                             data-meta-observation="<?= $i ?>"
                                             data-meta-imagenum="<?= $j ?>"
                                             data-crop-ratio="1.3333"
                                             <?php if(file_exists($path)): ?>data-initial-image="<?= $src ?>" <?php endif; ?>>
                                        </div>
                                        <small class="form-text text-muted">Image <?= $j ?></small>
                                    </div>
                                    <?php endfor; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="card-footer"></div>
                </div>
                <?php endforeach; ?>

            </div>
            <button type="button" class="btn btn-secondary btn-sm add-observation" data-group="<?= $grp ?>">
                Add Observation
            </button>
        </div>

        <?php endforeach; ?>
    </div>

    <!-- Pagination -->
    <nav>
        <ul class="pagination justify-content-center">
            <?php for($p=1;$p<=$totalPages;$p++): ?>
            <li class="page-item <?= $p===1?'active':'' ?>"><a class="page-link" href="#" onclick="showPage(<?= $p ?>);return false;"><?= $p ?></a></li>
            <?php endfor; ?>
        </ul>
    </nav>

    <!-- Surveyor & Inspection Date -->
    <div class="card mb-3">
        <div class="card-body row g-3">
            <div class="col-md-6">
                <label class="form-label">Surveyor</label>
                <select name="surveyor_id" class="form-select" data-mdb-select-init data-mdb-filter="true">
                    <option value="">Select Surveyor</option>
                    <?php foreach($surveyors as $s): ?>
                    <option value="<?= $s['id'] ?>" <?= $inspector==$s['id']?'selected':'' ?>>
                        <?= htmlspecialchars($s['forename'].' '.$s['surname'],ENT_QUOTES) ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-6">
                <label class="form-label">Date of Inspection</label>
                <input type="date" name="inspection_date" class="form-control" value="<?= htmlspecialchars($insp_date,ENT_QUOTES) ?>">
            </div>
        </div>
    </div>

    <!-- Actions -->
    <div class="d-flex justify-content-between mt-3">
        <button type="button" class="btn btn-success" onclick="saveInspection()">Save Progress</button>
        <button type="button" class="btn btn-info" onclick="markComplete()">Mark Complete</button>
        <button type="button" class="btn btn-danger" onclick="clearAll()">Clear All</button>
    </div>
</form>

<script>
// Pagination (unchanged)
function showPage(pg) {
    // 1) Hide everything...
    document.querySelectorAll('.circuit-card').forEach(c => c.style.display = 'none');
    document.querySelectorAll('.observation-panel').forEach(o => o.style.display = 'none');

    // 2) Show only this page’s cards & panel
    document.querySelectorAll(`.circuit-card[data-page='${pg}']`).forEach(c => c.style.display = 'block');
    const grp = <?= json_encode($allGroups) ?>[pg - 1];
    document.querySelector(`.observation-panel[data-group='${grp}']`).style.display = 'block';

    // 3) Update pagination active state
    document.querySelectorAll('.pagination .page-item').forEach(li => li.classList.remove('active'));
    const activeLink = document.querySelector(`.pagination .page-item a[onclick*="showPage(${pg})"]`);
    if (activeLink) activeLink.parentElement.classList.add('active');

    // 4) Scroll back to the top
    window.scrollTo({
        top: 0,
        behavior: 'smooth'
    });
}



// single-observation HTML template (without the <script> placeholders)
// __GRP__ and __IDX__ will be replaced in code
function buildObservationCard(grp, idx) {
    // fault‐code + textarea + FI checkbox
    const obsRow = document.createElement('div');
    obsRow.className = 'card mb-3 obs-card';
    obsRow.innerHTML = `
    <div class="card-header d-flex justify-content-between align-items-center">
      <span>Observation #${idx+1}</span>
      <button type="button" class="btn btn-sm btn-danger remove-observation" data-idx="${idx}">
        <i class="fas fa-trash"></i>
      </button>
    </div>
    <div class="card-body">
      <div class="row g-3 mb-2 obs-row">
        <div class="col-md-2">
          <label>Fault Code</label>
          <select name="observations[${grp}][${idx}][fault_code]" class="form-select form-select-sm">
            <option value="C1">C1</option>
            <option value="C2">C2</option>
            <option value="C3">C3</option>
            <option value="FI">FI</option>
          </select>
        </div>
        <div class="col-md-8">
          <label>Observations</label>          
                                <div class="d-flex">
                                    <textarea id="observations[${grp}][${idx}][text]" name="observations[${grp}][${idx}][text]" class="form-control form-control-sm" rows="2"></textarea>
                                    <div class="d-flex flex-column">
                                        <button type="button" class="btn btn-secondary mb-1 ms-4" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Clear Field"
                                                onClick="clearbox('observations[${grp}][${idx}][text]')">
                                            <i class="fad fa-eraser"></i>
                                        </button>
                                        <?php if($_SESSION['usertype']=="admins"){ ?>
                                        <button type="button" class="btn btn-info mb-1 ms-4" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="View List"
                                                onClick="autofillElec('formComplete','observations[${grp}][${idx}][text]','elecphrases')">
                                            <i class="fad fa-edit"></i>
                                        </button>
                                        <button type="button" class="btn btn-success mb-1 ms-4" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Save field as new entry"
                                                onClick="savebox('observations[${grp}][${idx}][text]','elecphrases')">
                                            <i class="fad fa-save"></i>
                                        </button>
                                        <?php } else { ?>
                                        <button type="button" class="btn btn-success mb-1 ms-4" onClick="javascript:void(0)"></button>
                                        <button type="button" class="btn btn-info mb-1 ms-4" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="View List"
                                                onClick="autofillElec('formComplete','observations[${grp}][${idx}][text]','elecphrases')">
                                            <i class="fad fa-edit"></i>
                                        </button>
                                        <?php } ?>
                                        <button type="button" class="btn btn-danger btn-info-alt ms-4" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Reset FIeld"
                                                onClick="resetBox('observations[<?= $grp ?>][<?= $idx ?>][text]')">
                                            <i class="fad fa-refresh"></i>
                                        </button>
                                    </div>
                                </div>
          
        </div>
        <div class="col-md-2 text-center form-check">
          <label>FI Y/N</label><br>
          <input type="checkbox" name="observations[${grp}][${idx}][fi]" class="form-check-input" value="1">
        </div>
      </div>
      <div class="row mb-3 img-row">
        <div class="col-12">
          <label>Upload Images</label>
          <div class="row image-uploads" data-group="${grp}" data-obs="${idx}">
            ${[1,2,3,4,5,6].map(i=>`
              <div class="col-lg-2 col-md-4 col-6 mb-2">
                <div class="imup"
                     data-service="images/elec_save.php"
                     data-target="${MASTER_REPORT_ID}_${BOARD_ID}_${grp}_${idx}_${i}.jpg"
                     data-meta-reportid="${MASTER_REPORT_ID}"
                     data-meta-boardid="${BOARD_ID}"
                     data-meta-group="${grp}"
                     data-meta-observation="${idx}"
                     data-meta-imagenum="${i}"
                     data-crop-ratio="1.3333"></div>
                <small class="form-text text-muted">Image ${i}</small>
              </div>`).join('')}
          </div>
        </div>
      </div>
    </div>
    <div class="card-footer"></div>
  `;
    return obsRow;
}

// add-observation
document.querySelectorAll('.add-observation').forEach(btn => {
    btn.addEventListener('click', () => {
        const grp = btn.getAttribute('data-group');
        const panel = document.querySelector(`.observation-panel[data-group='${grp}']`);
        const idx = panel.querySelectorAll('.obs-card').length;
        const card = buildObservationCard(grp, idx);
        // Insert the new card right before the button:
        panel.insertBefore(card, btn);

        // Initialize uploaders inside that card only:
        initializeImageUploaders({
            uploadUrl: 'images/elec_save.php',
            cropRatio: 1,
            removeUrl: 'images/elec_remove.php'
        });
    });
});

// remove-observation
document.addEventListener('click', e => {
    const btn = e.target.closest('.remove-observation');
    if (!btn) return;

    const card = btn.closest('.obs-card');
    const panel = card.closest('.observation-panel');
    const grp = panel.dataset.group;
    const obs = Number(btn.dataset.idx);

    alertMessage(
        'Confirm deletion',
        `Delete Observation #${obs+1} and all its images?`,
        () => {
            const body = new URLSearchParams();
            body.append('tenant', TENANT_URL);
            body.append('master_report_id', MASTER_REPORT_ID);
            body.append('board_id', BOARD_ID);
            body.append('group', grp);
            body.append('obs', obs);

            fetch(`${ROOT_URL}/includes/elec/delete_observation.php`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: body.toString()
                })
                .then(r => r.json())
                .then(json => {
                    if (json.success) {
                        // close the confirm modal
                        killModal('confirmBox');

                        // remove from the DOM
                        card.remove();

                        // re-number remaining cards in this panel
                        panel.querySelectorAll('.obs-card').forEach((c, idx) => {
                            c.querySelector('.card-header').textContent = `Observation #${idx+1}`;
                            const rm = c.querySelector('.remove-observation');
                            if (rm) rm.dataset.idx = idx;
                        });

                        showResponse('success', 'Observation removed');
                    } else {
                        showResponse('danger', 'Failed: ' + json.message);
                    }
                })
                .catch(() => showResponse('danger', 'Error deleting observation'));
        }
    );
});



// Action-button helpers (unchanged)
function disableHiddenPanels() {
    document.querySelectorAll('.observation-panel').forEach(p => {
        if (p.style.display === 'none') {
            p.querySelectorAll('input,select,textarea').forEach(i => i.disabled = true);
        }
    });
}

function saveInspection() {
    disableHiddenPanels();
    saveCircuitStage5('<?= $board_id ?>');
}

function markComplete() {
    disableHiddenPanels();
    markStageComplete5('<?= $board_id ?>');
}

function clearAll() {
    alertMessage('Confirm clear and reset',
        'This will clear all inspection data and uploaded images all data for this board. Are you sure?',
        () => clearStage5('<?= $board_id ?>'));
    disableHiddenPanels();

}

// Initialize first view + uploaders
showPage(1);
initializeImageUploaders({
    uploadUrl: 'images/elec_save.php',
    cropRatio: 1,
    removeUrl: 'images/elec_remove.php'
});

function openSidebar() {
    document.getElementById("offCanvasSidebar").classList.add("open");
}

function closeSidebar() {
    document.getElementById("offCanvasSidebar").classList.remove("open");
}

function selectCircuit(circuitNo) {
    const card = document.getElementById("circuit-" + circuitNo);
    if (!card) return;
    const page = card.getAttribute("data-page");
    showPage(page);
    setTimeout(() => {
        card.scrollIntoView({
            behavior: "smooth",
            block: "start"
        });
    }, 300);
    closeSidebar();
}

document.addEventListener('click', function(event) {
    var sidebar = document.getElementById('offCanvasSidebar');
    var toggleButton = document.getElementById('openSidebarBtn');
    if (sidebar.classList.contains('open') &&
        !sidebar.contains(event.target) &&
        !toggleButton.contains(event.target)) {
        closeSidebar();
    }
});
</script>