<?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>';

// -------------------------
// Step 1: Retrieve Existing Report Data (if any)
// -------------------------
$master_report_id = $_GET['master_report_id'] ?? null;

if ($master_report_id) {
    // Fetch the report data for the given master_report_id
    $query = "SELECT circuit_results FROM elec_report WHERE master_report_id = ? AND board_id=?";
    $stmt = $con->prepare($query);
    $stmt->bind_param("si", $master_report_id,$_GET['board_id'],); // Use master_report_id for the query
    $stmt->execute();
    $result = $stmt->get_result();
    $reportData = $result->fetch_assoc();
    $stmt->close();
}

// Decode JSON stored in the circuit_results column (if available)
$circuitData = !empty($reportData['circuit_results'])
    ? json_decode($reportData['circuit_results'], true)
    : [];

// -------------------------
// Step 2: Query the elec_circuit Table for Circuit Details for the selected board
// -------------------------
$query = "SELECT circuit_id, circuit_no, circuit_description FROM elec_circuit WHERE board_id = ? ORDER BY circuit_no ASC";
$stmt = $con->prepare($query);
$stmt->bind_param("i", $board_id);
$stmt->execute();
$result = $stmt->get_result();
$circuitsInfo = [];
while ($row = $result->fetch_assoc()){
    $circuitsInfo[$row['circuit_id']] = $row;
}
$stmt->close();

// Build the complete circuit data array (using saved values if available)
$completeCircuitData = [];
foreach ($circuitsInfo as $id => $info) {
    if (isset($circuitData[$id])) {
        $data = $circuitData[$id];
        // Ensure these keys are present by falling back to table data if needed.
        $data['circuit_no'] = $data['circuit_no'] ?? $info['circuit_no'];
        $data['circuit_description'] = $data['circuit_description'] ?? $info['circuit_description'];
        $completeCircuitData[$id] = $data;
    } else {
        $completeCircuitData[$id] = [
            'circuit_no'          => $info['circuit_no'],
            'circuit_description' => $info['circuit_description'],
            'r1'                  => '',
            'rn'                  => '',
            'r2'                  => '',
            'r1_r2'               => '',
            'r2_continuity'       => '',
            'pp'                  => '',
            'pe'                  => '',
            'polarity'            => 0,
            'zs'                  => '',
            'earth_leakage'       => '',
            'rcd_trip_time'       => '',
            'rcd_functional'      => 0,
            'afdd_functional'     => 0,
            'observations'        => ''
        ];
    }
}

// -------------------------
// Step 3: Setup Client-Side Pagination for the circuits
// -------------------------
$allCircuitIds = array_keys($completeCircuitData);
sort($allCircuitIds, SORT_NUMERIC);
$totalCircuits = count($allCircuitIds);
$circuitsPerPage = 3;  // Show 3 circuits per page
$totalPages = ($totalCircuits > 0) ? ceil($totalCircuits / $circuitsPerPage) : 1;

$groupedCircuits = [];
foreach ($completeCircuitData as $circuitId => $circuit) {
    // Extract numeric portion from circuit_no (e.g. "1" from "1L1")
    if (preg_match('/^(\d+)/', $circuit['circuit_no'], $matches)) {
        $group = $matches[1];
    } else {
        $group = 'Unknown';
    }
    if (!isset($groupedCircuits[$group])) {
        $groupedCircuits[$group] = [];
    }
    $groupedCircuits[$group][] = [
        'circuit_id'          => $circuitId,
        'circuit_no'          => $circuit['circuit_no'],
        'circuit_description' => $circuit['circuit_description']
    ];
}
ksort($groupedCircuits);


// Step 5: Final Data
?>
<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("<?php echo addslashes($circuit["circuit_id"]); ?>"); 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>

<!-- Begin Form (all circuits loaded at once) -->
<form id="circuitInspectionForm" enctype="multipart/form-data">

    <!-- Container for All Circuit Cards -->
    <div id="circuitContainer">
        <?php
        $index = 0;
        foreach ($allCircuitIds as $circuitId) {
            $index++;
            $pageNumber = floor(($index - 1) / $circuitsPerPage) + 1;
            $circuit = $completeCircuitData[$circuitId];
            $displayStyle = ($pageNumber == 1) ? 'block' : 'none';
            $circuitNo = $circuit['circuit_no'];
            $ending = substr($circuitNo, -2);
            $headerStyle = "";
            if ($ending === "L1") {
                $headerStyle = "background-color:darkred!important; color:white;";
            } elseif ($ending === "L2") {
                $headerStyle = "background-color:black!important; color:white;";
            } elseif ($ending === "L3") {
                $headerStyle = "background-color:darkgrey!important; color:white;";
            }
            ?>
        <div class="circuit-card" data-page="<?php echo $pageNumber; ?>" id="circuit-<?php echo htmlspecialchars($circuitId, ENT_QUOTES, 'UTF-8'); ?>" style="display: <?php echo $displayStyle; ?>;">
            <div class="card mb-3">
                <div class="card-header bg-light" style="<?php echo $headerStyle; ?>">
                    <h5 class="mb-0">
                        Circuit <?php echo htmlspecialchars($circuit['circuit_no'], ENT_QUOTES, 'UTF-8'); ?>:
                        <?php echo htmlspecialchars($circuit['circuit_description'], ENT_QUOTES, 'UTF-8'); ?>
                    </h5>
                </div>
                <div class="card-body">
                    <!-- First Row: Four Columns -->
                    <div class="row">
                        <!-- Column 1: Continuity -->
                        <div class="col-lg-3">
                            <h6 class="text-primary">Continuity</h6>
                            <div class="mb-2">
                                <label>r1 (Ω)</label>
                                <input type="text" class="form-control form-control-sm" name="circuit_results[<?php echo $circuitId; ?>][r1]" value="<?php echo htmlspecialchars($circuit['r1'], ENT_QUOTES, 'UTF-8'); ?>" required>
                            </div>
                            <div class="mb-2">
                                <label>rn (Ω)</label>
                                <input type="text" class="form-control form-control-sm" name="circuit_results[<?php echo $circuitId; ?>][rn]" value="<?php echo htmlspecialchars($circuit['rn'], ENT_QUOTES, 'UTF-8'); ?>" required>
                            </div>
                            <div class="mb-2">
                                <label>r2 (Ω)</label>
                                <input type="text" class="form-control form-control-sm" name="circuit_results[<?php echo $circuitId; ?>][r2]" value="<?php echo htmlspecialchars($circuit['r2'], ENT_QUOTES, 'UTF-8'); ?>" required>
                            </div>
                            <div class="mb-2">
                                <label>R1+R2 (Ω)</label>
                                <input type="text" class="form-control form-control-sm" name="circuit_results[<?php echo $circuitId; ?>][r1_r2]" value="<?php echo htmlspecialchars($circuit['r1_r2'], ENT_QUOTES, 'UTF-8'); ?>" required>
                            </div>
                            <div class="mb-2">
                                <label>R2 (Ω)</label>
                                <input type="text" class="form-control form-control-sm" name="circuit_results[<?php echo $circuitId; ?>][r2_continuity]" value="<?php echo htmlspecialchars($circuit['r2_continuity'], ENT_QUOTES, 'UTF-8'); ?>"
                                       required>
                            </div>
                        </div>
                        <!-- Column 2: Insulation Resistance -->
                        <div class="col-lg-3">
                            <h6 class="text-primary">Insulation Resistance</h6>
                            <div class="mb-2">
                                <label>P/P (MΩ)</label>
                                <input type="text" class="form-control form-control-sm" name="circuit_results[<?php echo $circuitId; ?>][pp]" value="<?php echo htmlspecialchars($circuit['pp'], ENT_QUOTES, 'UTF-8'); ?>" required>
                            </div>
                            <div class="mb-2">
                                <label>P/E (MΩ)</label>
                                <input type="text" class="form-control form-control-sm" name="circuit_results[<?php echo $circuitId; ?>][pe]" value="<?php echo htmlspecialchars($circuit['pe'], ENT_QUOTES, 'UTF-8'); ?>" required>
                            </div>
                        </div>
                        <!-- Column 3: Polarity, Measured Zs, Earth Leakage -->
                        <div class="col-lg-3">
                            <h6 class="text-primary">Polarity</h6>
                            <div class="mb-2">
                                <label>Polarity Confirmed</label><br>
                                <?php $checked = ($circuit['polarity'] == 1) ? 'checked' : ''; ?>
                                <input type="checkbox" class="form-check-input" name="circuit_results[<?php echo $circuitId; ?>][polarity]" value="1" <?php echo $checked; ?>>
                            </div>
                            <h6 class="text-primary">Measured Zs</h6>
                            <div class="mb-2">
                                <label>Zs (Ω)</label>
                                <input type="text" class="form-control form-control-sm" name="circuit_results[<?php echo $circuitId; ?>][zs]" value="<?php echo htmlspecialchars($circuit['zs'], ENT_QUOTES, 'UTF-8'); ?>" required>
                            </div>
                            <h6 class="text-primary">Earth Leakage</h6>
                            <div class="mb-2">
                                <label>Earth Leakage (mA)</label>
                                <input type="text" class="form-control form-control-sm" name="circuit_results[<?php echo $circuitId; ?>][earth_leakage]" value="<?php echo htmlspecialchars($circuit['earth_leakage'], ENT_QUOTES, 'UTF-8'); ?>"
                                       required>
                            </div>
                        </div>
                        <!-- Column 4: RCD and AFDD -->
                        <div class="col-lg-3">
                            <h6 class="text-primary">RCD</h6>
                            <div class="mb-2">
                                <label>RCD Trip Time (ms)</label>
                                <input type="text" class="form-control form-control-sm" name="circuit_results[<?php echo $circuitId; ?>][rcd_trip_time]" value="<?php echo htmlspecialchars($circuit['rcd_trip_time'], ENT_QUOTES, 'UTF-8'); ?>"
                                       required>
                            </div>
                            <div class="mb-2">
                                <label>RCD Functional Test</label><br>
                                <?php $checked = ($circuit['rcd_functional'] == 1) ? 'checked' : ''; ?>
                                <input type="checkbox" class="form-check-input" name="circuit_results[<?php echo $circuitId; ?>][rcd_functional]" value="1" <?php echo $checked; ?>>
                            </div>
                            <h6 class="text-primary">AFDD</h6>
                            <div class="mb-2">
                                <label>AFDD Functional Test</label><br>
                                <?php $checked = ($circuit['afdd_functional'] == 1) ? 'checked' : ''; ?>
                                <input type="checkbox" class="form-check-input" name="circuit_results[<?php echo $circuitId; ?>][afdd_functional]" value="1" <?php echo $checked; ?>>
                            </div>
                        </div>
                    </div><!-- End first row -->

                    <!-- Additional Details Row -->
                    <div class="row">
                        <div class="col-12">
                            <h6 class="text-primary">Additional Details</h6>
                            <div class="mb-2">
                                <label>Observations</label>
                                <div class="d-flex">
                                    <textarea class="form-control form-control-sm" id="circuit_results[<?php echo $circuitId; ?>][observations]" name="circuit_results[<?php echo $circuitId; ?>][observations]"
                                              rows="2"><?php echo htmlspecialchars($circuit['observations'], ENT_QUOTES, 'UTF-8'); ?></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('circuit_results[<?php echo $circuitId; ?>][observations]')">
                                            <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','circuit_results[<?php echo $circuitId; ?>][observations]','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('circuit_results[<?php echo $circuitId; ?>][observations]','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','circuit_results[<?php echo $circuitId; ?>][observations]','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('circuit_results[<?php echo $circuitId; ?>][observations]')">
                                            <i class="fad fa-refresh"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div class="mb-2 imageContainer">
                                <label>Upload Image</label>
                                <div class="row">
                                    <?php 
                                    // Loop to output 6 separate image upload placeholders
                                    for ($img = 1; $img <= 6; $img++): 
                                        $reportid = $master_report_id;
                                        $checkedImage = TENANT_DEFER."/images/report_images/{$reportid}_{$board_id}_{$circuitId}_{$img}.jpg";
                                        $expectedImage = "images/report_images/{$reportid}_{$board_id}_{$circuitId}_{$img}.jpg";
                                        $targetImage = "{$reportid}_{$board_id}_{$circuitId}_{$img}.jpg";
                                    ?>
                                    <div class="col-lg-2 col-md-4 col-6 mb-2" style="position: relative;">
                                        <div class="card p-0 m-0">
                                            <div class="card-body p-2">
                                                <div class="imup p-0 m-0"
                                                     data-label="Select Image"
                                                     data-service="images/elec_save.php"
                                                     data-target="<?= $targetImage ?>"
                                                     data-meta-reportid="<?php echo $reportid; ?>"
                                                     data-meta-boardid="<?php echo $board_id; ?>"
                                                     data-meta-circuitid="<?php echo $circuitId; ?>"
                                                     data-meta-imagenum="<?php echo $img; ?>"
                                                     data-crop-ratio="1.3333"
                                                     <?php if (file_exists($checkedImage)): ?>
                                                     data-initial-image="<?= $expectedImage ?>"
                                                     <?php endif; ?>>
                                                </div>
                                                <small class="form-text text-muted">Image <?php echo $img; ?></small>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endfor; ?>
                                </div>
                            </div>
                        </div>
                    </div><!-- End Additional Details Row -->

                    <!-- Hidden input for circuit id -->
                    <input type="hidden" name="circuit_results[<?php echo $circuitId; ?>][circuit_id]" value="<?php echo htmlspecialchars($circuitId, ENT_QUOTES, 'UTF-8'); ?>">
                </div><!-- End card-body -->
            </div><!-- End card -->
        </div><!-- End circuit-card -->
        <?php } // end foreach ?>
    </div><!-- End circuitContainer -->

    <!-- Pagination Controls -->
    <nav aria-label="Circuit results pagination">
        <ul class="pagination justify-content-center">
            <?php if ($totalPages > 1): ?>
            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
            <li class="page-item <?php echo ($i == 1) ? 'active' : ''; ?>">
                <a class="page-link" href="#" onclick="showCircuitPage(<?php echo $i; ?>); return false;"><?php echo $i; ?></a>
            </li>
            <?php endfor; ?>
            <?php endif; ?>
        </ul>
    </nav>

    <!-- Action Buttons -->
    <div class="row mt-4">
        <div class="d-flex justify-content-between align-items-center mt-4">

            <button type="button" class="btn btn-success" onclick="alertMessage('Confirm Save', 'Are you sure you want to save this stage?', () => saveCircuitStage4('<?php echo $board_id; ?>'))">Save Progress</button>
            <button id="markCompleteBtn" type="button" class="btn btn-info mx-auto"
                    onclick="alertMessage('Confirm Completion', 'Are you sure you want to mark this stage as complete?', () => markStageComplete4('<?php echo $board_id; ?>'))">Mark Complete</button>
            <button id="clearStageBtn" type="button" class="btn btn-danger" onclick="alertMessage('Confirm Clear', 'This will reset all data for this stage. Are you sure?', () => clearStage4('<?php echo $board_id; ?>'))">Clear
                all</button>

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

<!-- Client-side Pagination Script -->
<script>
initializeImageUploaders({
    uploadUrl: "default-upload.php",
    cropRatio: 1,
    removeUrl: "images/elec_remove.php"
});

setTimeout(function() {
    showCircuitPage(1);
}, 1000);

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

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

function selectCircuit(circuitId) {
    var circuitEl = document.getElementById("circuit-" + circuitId);
    if (!circuitEl) return;
    var pageNumber = circuitEl.getAttribute("data-page");
    if (!pageNumber) return;
    showCircuitPage(pageNumber);
    setTimeout(function() {
        circuitEl.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>