<?php
// elec_new_report.php

// Extract board data from the pipe-delimited string in $_REQUEST['data']
$d = explode("|", $_REQUEST['data']);
if (!isset($d[0])) {
    die("Error: Board ID is missing.");
}
$board_id     = intval($d[0]);
$clientnumber = intval($d[1]);
$locnumber    = intval($d[2]);

// Fetch Board Details
function get_board_details($board_id) {
    global $con;
    $query = "SELECT b.*, l.locname, l.postcode
              FROM elec_board b
              LEFT JOIN locations l ON b.locnumber = l.locnumber
              WHERE b.board_id = ?";
    $stmt = $con->prepare($query);
    if (!$stmt) {
        die("Prepare failed: " . $con->error);
    }
    $stmt->bind_param("i", $board_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    $stmt->close();

    if ($row) {
        $row['clientname'] = !empty($row['clientnumber']) ? getClientName($row['clientnumber']) : 'Unknown';
        $row['locname'] = !empty($row['locname']) ? $row['locname'].' ('.$row['postcode'].')' : 'Unknown';
        // Remove these fields from the output
        unset($row['locnumber'], $row['clientnumber'], $row['postcode'], $row['board_id']);
        if (!empty($row['installation_date'])) {
            $dt = DateTime::createFromFormat('Y-m-d', $row['installation_date']);
            if ($dt !== false) {
                $row['installation_date'] = $dt->format('d-m-Y');
            } else {
                $timestamp = strtotime($row['installation_date']);
                if ($timestamp !== false) {
                    $row['installation_date'] = date('d-m-Y', $timestamp);
                }
            }
        }
        // Convert any 1/0 values to Yes/No for display
        foreach ($row as $key => $value) {
            if ($value === "1" || $value === 1) {
                $row[$key] = "Yes";
            } elseif ($value === "0" || $value === 0) {
                $row[$key] = "No";
            }
        }
        return $row;
    }
    return [];
}

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

$circuitsInfo = [];
while ($row = $result->fetch_assoc()) {
    $parts = json_decode($row['parts'], true) ?: [];
    $circuitsInfo[$row['circuit_id']] = [
        'circuit_id'      => (int)$row['circuit_id'],
        'circuit_number'  => $row['circuit_number'],
        'parts'           => $parts
    ];
}
$stmt->close();

$circuitsCount = count($circuitsInfo);

// Check for an incomplete report for this board
function check_incomplete_report($board_id) {
    global $con;
    $query = "SELECT master_report_id FROM elec_report WHERE board_id = ? AND status = 'active'";
    $stmt = $con->prepare($query);
    $stmt->bind_param("i", $board_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $data = $result->fetch_assoc();
    $stmt->close();
    return $data;
}

$board_details = get_board_details($board_id);

// Check for an incomplete report
$incomplete_report = check_incomplete_report($board_id);

// Determine master_report_id
$master_report_id = !empty($incomplete_report['master_report_id']) ? $incomplete_report['master_report_id'] : null;
echo '

<script>
const CIRCUITS ='.json_encode(array_values($circuitsInfo)).';
let MASTER_REPORT_ID = '.json_encode($master_report_id) .';
let is_update = MASTER_REPORT_ID !== null;
</script>';

// Surveyor functions
function getSurveyorNameForm($esname){
$stmt = $GLOBALS['con']->prepare("SELECT `surname`,`forename` FROM `surveyor` WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i', $esname);
$stmt->execute();
$rc = $stmt->get_result();
$stmt->close();
$cd = mysqli_fetch_array($rc);
return $cd['forename']." ".$cd['surname'];
}

function listSurveyor($c, $n, $t){
if(!empty($_SESSION['contractorNumber'])){
$filter = "AND `contractor`='".$_SESSION['contractorNumber']."'";
}
switch($t){
case "select":
$ca = array();
$stmt = $GLOBALS['con']->prepare("SELECT `id`,`esname`,`forename`,`surname` FROM `surveyor` WHERE `statuslive`='1' ORDER BY `forename` ASC") or die(mysqli_error($GLOBALS['con']));
$stmt->execute();
$cc = $stmt->get_result();
$stmt->close();
while($pd = mysqli_fetch_array($cc)) { $ca[] = $pd; }
$ret = '<select class="form-control form-control-sm" data-mdb-select-init data-mdb-filter="true" id="'.$n.'" name="'.$n.'">';
    $ret .= '<option value="NULL">Select primary Surveyor</option>';
    foreach($ca as $px){
    $name = $px['forename'].' '.$px['surname'];
    $s = ($c == $px['id']) ? "SELECTED" : "";
    $ret .= '<option value="'.$px['id'].'" '.$s.'>'.$name.'</option>';
    }
    $ret .= '</select>';
return $ret;
break;
case "name":
$ca = array();
$stmt = $GLOBALS['con']->prepare("SELECT `id`,`esname`,`forename`,`surname` FROM `surveyor` WHERE `statuslive`='1' ORDER BY `forename` ASC") or die(mysqli_error($GLOBALS['con']));
$stmt->execute();
$cc = $stmt->get_result();
$stmt->close();
while($pd = mysqli_fetch_array($cc)) { $ca[] = $pd; }
$ret = '<select class="form-control form-control-sm" id="'.$n.'" name="'.$n.'">';
    $ret .= '<option value="NULL">Select Surveyor</option>';
    foreach($ca as $px){
    $name = $px['forename'].' '.$px['surname'];
    $s = ($c == $name) ? "SELECTED" : "";
    $ret .= '<option value="'.$name.'" '.$s.'>'.$name.'</option>';
    }
    $ret .= '</select>';
return $ret;
break;
case "ajax":
$ca = array();
$stmt = $GLOBALS['con']->prepare("SELECT `id`,`esname`,`forename`,`surname` FROM `surveyor` WHERE `statuslive`='1' ORDER BY `forename` ASC") or die(mysqli_error($GLOBALS['con']));
$stmt->execute();
$cc = $stmt->get_result();
$stmt->close();
$cnt = mysqli_num_rows($cc);
while($pd = mysqli_fetch_array($cc)) { $ca[] = $pd; }
$co = 0;
$ret = 'var clientList = [';
foreach($ca as $px){
$name = $px['forename'].' '.$px['surname'];
$name = str_replace('"','',$name);
$name = str_replace('\&','and',$name);
$co++;
$s = ($co == $cnt) ? "" : ",";
$ret .= '{"value":"'.$name.'","name":"'.$px['id'].'"}'.$s."\n";
}
$ret .= '];';
return $ret;
break;
}
}

// Build board list using both clientnumber and locnumber
$locationBoards = [];
$query = "SELECT board_id, board_name FROM elec_board WHERE clientnumber = ? AND locnumber = ?";
$stmt = $con->prepare($query);
$stmt->bind_param("ii", $clientnumber, $locnumber);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()){
$locationBoards[] = $row;
}
$stmt->close();
?>


<!-- Pass the full board list to JavaScript and as a hidden field for saves -->
<script>
const ALL_BOARD_LIST = <?= json_encode($locationBoards) ?>;
var locationBoards = ALL_BOARD_LIST;
</script>
<input type="hidden" id="board_list" name="board_list" value='<?= htmlspecialchars(json_encode($locationBoards, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), ENT_QUOTES, 'UTF-8') ?>'>


<style>
#toggleBoardDetails {
    position: fixed;
    top: 48px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 1050;
}

#boardDetailsContainer {
    position: fixed;
    top: 48px;
    left: 50%;
    transform: translateX(-50%);
    width: 90%;
    max-width: 800px;
    z-index: 1040;
}
</style>

<div class="collapse bg-info text-light p-3 border shadow-4-strong rounded-bottom"
     id="boardDetailsContainer">
    <h2>All Boards Overview</h2>

    <?php if (count($locationBoards) === 0): ?>
    <p class="text-light">No boards found for this client/location.</p>
    <?php else: ?>
    <!-- Make this inner wrapper a fixed height with vertical scrolling -->
    <div class="board-list-scroll bg-dark text-light rounded"
         style="max-height: 400px; overflow-y: auto; padding: 0.5rem;">
        <?php foreach ($locationBoards as $b): 
          $b_id    = intval($b['board_id']);
          $details = get_board_details($b_id);
      ?>
        <div class="mb-3">
            <div class="p-2 bg-secondary rounded">
                <h5 class="note note-dark text-secondary mb-2"><?= htmlspecialchars($b['board_name']) ?></h5>
                <?php if (!empty($details)): ?>
                <div class="row">
                    <?php 
                $i = 0;
                foreach ($details as $field => $value):
                  $label = ucwords(str_replace('_',' ',$field));
                ?>
                    <div class="col-6 mb-1">
                        <span style="color:darkgrey;"><?= htmlspecialchars($label) ?>:</span>:
                        <span><?= htmlspecialchars($value) ?></span>
                    </div>
                    <?php 
                  $i++;
                  if ($i % 2 === 0 && $i < count($details)) {
                    echo '</div><div class="row">'; 
                  }
                endforeach; 
                ?>
                </div>
                <?php else: ?>
                <p class="text-light mb-0">No details available.</p>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

</div>
<button id="toggleBoardDetails" class="btn btn-secondary" type="button"
        data-mdb-toggle="collapse"
        data-mdb-target="#boardDetailsContainer"
        aria-expanded="false"
        aria-controls="boardDetailsContainer">
    Board Details
</button>

<link rel="stylesheet" href="<?= ROOT_URL ?>/src/uploader.css?v=5.0.3">
<div class="container-fluid">
    <div class="row mb-4 pt-3">
        <div class="col-md-8">
            <h3 class="text-dark">
                <?= $incomplete_report 
                    ? '<i class="fad fa-regular fa-arrow-right-to-bracket"></i> Resume Report' 
                    : '<i class="fad fa-regular fa-square-plus"></i> Create New Report' ?>
            </h3>
            <p>
                Board: <?= htmlspecialchars($board_details['board_name']) ?>
                Location: <?= htmlspecialchars($board_details['locname']) ?>
            </p>
        </div>
        <div class="col-md-4 text-md-end text-center">
            <button class="btn btn-secondary mt-3" onclick="window.history.back()">
                <i class="fas fa-arrow-left"></i> Cancel
            </button>
        </div>
    </div>

    <div class="row">
        <div class="col-12 col-md-2">
            <h5>Report Stages</h5>
            <ul class="list-group" id="reportChecklist">
                <li class="list-group-item mb-2 p-2 border-top bg-info text-light" onclick="navigateStage(1)" style="cursor: pointer; font-size:12px">
                    1. Details of Installation
                    <span class="float-end" id="stage1-status">
                        <i class="fad fa-spinner-third text-info fa-spin"></i>
                    </span>
                </li>
                <li class="list-group-item mb-2 p-2 border-top bg-info text-light" onclick="navigateStage(2)" style="cursor: pointer; font-size:12px">
                    2. Schedule of Inspection
                    <span class="float-end" id="stage2-status">
                        <i class="fad fa-spinner-third text-info fa-spin"></i>
                    </span>
                </li>
                <li class="list-group-item mb-2 p-2 border-top bg-info text-light" onclick="navigateStage(3)" style="cursor: pointer; font-size:12px">
                    3. Condition Report
                    <span class="float-end" id="stage3-status">
                        <i class="fad fa-spinner-third text-info fa-spin"></i>
                    </span>
                </li>
                <li class="list-group-item mb-2 p-2 border-top bg-info text-light" onclick="navigateStage(4)" style="cursor:pointer;font-size:12px">
                    4. Observations
                    <span class="float-end" id="stage4-status">
                        <i class="fad fa-spinner-third text-info fa-spin"></i>
                    </span>
                </li>

            </ul>
            <h5>Inspection and Test Results (Per Board)</h5>
            <ul class="list-group" id="locationBoardsList">
                <?php foreach ($locationBoards as $board): ?>
                <li class="list-group-item mb-2 p-2 border-top bg-info text-light" onclick="navigateStage5(<?= $board['board_id'] ?>)" style="cursor: pointer; font-size:12px">
                    Board: <?= htmlspecialchars($board['board_name']) ?>
                    <span class="float-end" id="stage5-status-<?= $board['board_id'] ?>">
                        <i class="fad fa-spinner-third text-info fa-spin"></i>
                    </span>
                </li>
                <?php endforeach; ?>
            </ul>
            <div id="completeActions"></div>
        </div>
        <div class="col-12 col-md-10">
            <div id="stageContent">
                <div id="landingMessage" class="d-flex flex-column align-items-center justify-content-center my-5">
                    <span class="fa-stack fa-4x">
                        <i class="fad fa-square fa-stack-2x text-dark"></i>
                        <i class="fad fa-bolt fa-stack-1x text-light fa-inverse"></i>
                    </span>
                    <h2 class="mt-3 text-primary">Electrical Inspection Report</h2>
                    <p class="text-muted">Select a stage from the checklist to begin your inspection.</p>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/6.2.0/mdb.min.js"></script>
<script src="<?= ROOT_URL ?>/src/uploader.js"></script>
<script>
// Expose locationBoards array to JavaScript.
var locationBoards = <?= json_encode($locationBoards) ?>;

// Initialize MDB collapse for board details.
document.addEventListener('DOMContentLoaded', function() {
    if (typeof mdb !== 'undefined') {
        const element = document.querySelector('.collapse');
        new mdb.Collapse(element);
    } else {
        console.error("Error loading MDB");
    }
});

function alertMessage(title, message, target) {
    var dest = `<p>${message}</p>`;
    loadModalContent(dest, "confirmBox", "modal-md", 1060, "true", title, "cancelConfirm", target);
}

function toggleImageUploaders() {
    var reportId = MASTER_REPORT_ID;
    var uploaderContainers = document.querySelectorAll('.imageContainer');
    uploaderContainers.forEach(function(container) {
        var existingMsg = container.parentNode.querySelector('.uploader-message');
        if (!reportId) {
            container.style.display = "none";
            if (!existingMsg) {
                var message = document.createElement("div");
                message.className = "uploader-message";
                message.style.textAlign = "center";
                message.style.padding = "10px";
                message.style.fontWeight = "bold";
                message.textContent = "Image uploaders available after initial save";
                container.parentNode.insertBefore(message, container);
            }
        } else {
            container.style.display = "block";
            if (existingMsg) {
                existingMsg.remove();
            }
        }
    });
}

// Global navigation for stages 1-3 – now including board_list if available
function navigateStage(stage) {
    // Ensure ALL_BOARD_LIST is defined and non-empty before encoding
    var boardListParam = "";
    if (typeof ALL_BOARD_LIST !== "undefined" && ALL_BOARD_LIST.length > 0) {
        boardListParam = encodeURIComponent(JSON.stringify(ALL_BOARD_LIST));
    }
    // Build URL; note we pass locnumber and tenant; board_list is appended if available
    var url = `${ROOT_URL}/includes/elec/load_stage.php?stage=${stage}&locnumber=<?= $locnumber ?>&tenant=${TENANT_URL}`;
    if (boardListParam !== "") {
        url += `&board_list=${boardListParam}`;
    }

    loadContentAndExecuteScripts(url, "stageContent", "", function() {
        fetch(`${ROOT_URL}/includes/elec/get_report_status.php?master_report_id=${MASTER_REPORT_ID}&tenant=${TENANT_URL}`)

            .then(response => response.json())
            .then(response => {
                if (response.success) {
                    const data = response.data;
                    if (stage === 4) {
                        toggleImageUploaders();
                    }
                    var markCompleteBtn = document.getElementById('markCompleteBtn');
                    if (markCompleteBtn) {
                        markCompleteBtn.style.display = (data.stage_1_4[stage] === 'complete') ?
                            'none' :
                            'block';
                    }
                }
            })
            .catch(error => console.error('Error fetching report data:', error));
    });
}


// Navigation for Stage 5 (board‑specific)
function navigateStage5(boardId) {
    var boardListParam = encodeURIComponent(JSON.stringify(ALL_BOARD_LIST));
    var is_update = (MASTER_REPORT_ID !== null) ? "true" : "false"; // Check if it's update mode
    var url = `${ROOT_URL}/includes/elec/load_stage.php?stage=5&tenant=${TENANT_URL}&board_id=${boardId}&is_update=${is_update}&master_report_id=${MASTER_REPORT_ID}&board_list=${boardListParam}`;
    loadContentAndExecuteScripts(url, "stageContent", "", function() {
        fetch(`${ROOT_URL}/includes/elec/get_report_status.php?report_id=${MASTER_REPORT_ID}&tenant=${TENANT_URL}`)
            .then(response => response.json())
            .then(response => {
                if (response.success) {
                    var status = (response.data.circuit_results && response.data.circuit_results[boardId]) ? response.data.circuit_results[boardId] : "empty";
                    updateStage5Status(boardId, status);
                }
            })
            .catch(error => console.error('Error fetching report data:', error));
    });
}

//////////////////////////////////////////////////////////////////////////////////////////////////

function checkStageCompletion() {
    if (!MASTER_REPORT_ID) {
        // If there's no report ID (e.g., for new reports), set everything as "Not started"
        updateStageStatus(1, "empty"); // Not started
        updateStageStatus(2, "empty"); // Not started
        updateStageStatus(3, "empty"); // Not started
        updateStageStatus(4, "empty"); // Not started
        locationBoards.forEach(board => {
            const bid = board.board_id;

            updateStage5Status(bid, 'empty');
        });
        return;
    }

    // Fetch report status data from the server
    fetch(`${ROOT_URL}/includes/elec/get_report_status.php?master_report_id=${MASTER_REPORT_ID}&tenant=${TENANT_URL}`)
        .then(response => response.json())
        .then(response => {
            console.log('Fetched report data:', response); // Log the response data to the console for debugging

            if (response.success) {
                const data = response.data;

                // Update stages 1-3 status (same for all boards)
                updateStageStatus(1, data.stage_1_4[1] || 'empty'); // Default to 'empty' (Not started)
                updateStageStatus(2, data.stage_1_4[2] || 'empty'); // Default to 'empty' (Not started)
                updateStageStatus(3, data.stage_1_4[3] || 'empty'); // Default to 'empty' (Not started)
                updateStageStatus(4, data.stage_1_4[4] || 'empty'); // Default to 'empty' (Not started)


                // Update stage 4 status for each board (board-specific)
                for (const boardId in data.stage_5) {
                    const boardStatus = data.stage_5[boardId] || 'empty'; // Default to 'empty' if no status is found
                    updateStage5Status(boardId, boardStatus);
                }

                // If no status for any board, mark it as "Not started"
                for (const boardId in data.stage_5) {
                    if (!data.stage_5[boardId]) {
                        updateStage5Status(boardId, 'empty');
                    }
                }
            } else {
                console.error('Error fetching report data:', response.message);
            }
        })
        .catch(error => console.error('Error fetching report data:', error));

}

function updateStageStatus(stage, status) {
    const statusElem = document.getElementById("stage" + stage + "-status");
    if (statusElem) {
        let iconHTML = '';
        switch (status) {
            case 'complete':
                iconHTML = '<i class="fad fa-check-circle text-success"></i> Complete';
                break;
            case 'empty':
                iconHTML = '<i class="fad fa-minus-circle text-danger"></i> Not started';
                break;
            case 'ongoing':
                iconHTML = '<i class="fad fa-spinner-third text-info fa-spin"></i> Ongoing';
                break;
        }
        statusElem.innerHTML = iconHTML;
    }
}

function updateStage5Status(boardId, status) {
    const statusElem = document.getElementById("stage5-status-" + boardId);
    if (statusElem) {
        let iconHTML = '';
        switch (status) {
            case 'complete':
                iconHTML = '<i class="fad fa-check-circle text-success"></i> Complete';
                break;
            case 'empty':
                iconHTML = '<i class="fad fa-minus-circle text-danger"></i> Not started';
                break;
            case 'ongoing':
                iconHTML = '<i class="fad fa-spinner-third text-info fa-spin"></i> Ongoing';
                break;
        }
        statusElem.innerHTML = iconHTML;
    }
}


////////////////////////////////////////////////////////////////////////////////////////////////////

function checkAllStagesComplete() {
    fetch(`${ROOT_URL}/includes/elec/get_stage_status.php?master_report_id=${MASTER_REPORT_ID}&tenant=${TENANT_URL}`)
        .then(r => r.json())
        .then(response => {
            if (!response.success) {
                console.error('Error fetching stage status:', response.message);
                return;
            }
            const data = response.data;

            // stages 1–4 as you already have
            const s1 = data.stage_1_4[1] || 'empty';
            const s2 = data.stage_1_4[2] || 'empty';
            const s3 = data.stage_1_4[3] || 'empty';
            const s4 = data.stage_1_4[4] || 'empty';
            const all4Complete = [s1, s2, s3, s4].every(st => st === 'complete');

            // ────── NEW: Update stage-5 status for every board ──────
            locationBoards.forEach(board => {
                const bid = board.board_id;
                const st = (data.stage_5 && data.stage_5[bid]) ? data.stage_5[bid] : 'empty';
                updateStage5Status(bid, st);
            });

            // flatten stage5 statuses array:
            const stage5Statuses = locationBoards.map(b =>
                (data.stage_5 && data.stage_5[b.board_id]) || 'empty'
            );
            const any5Started = stage5Statuses.some(st => st !== 'empty');
            const all5Complete = stage5Statuses.length > 0 &&
                stage5Statuses.every(st => st === 'complete');

            // ---- always show CANCEL if any stage (1–4 or 5) has been started ----
            const anyStageStarted = [s1, s2, s3, s4].some(st => st !== 'empty') || any5Started;
            if (anyStageStarted) {
                if (!document.getElementById("cancelReportBtn")) {
                    const btn = document.createElement("button");
                    btn.id = "cancelReportBtn";
                    btn.className = "btn btn-sm btn-danger mt-4 me-5";
                    btn.innerText = "Cancel Report";
                    btn.addEventListener("click", () => {
                        alertMessage(
                            'Confirm Cancel',
                            'This will reset all data for this report. Are you sure?',
                            cancelReport
                        );
                    });
                    document.getElementById("completeActions").appendChild(btn);
                }
            } else {
                const existing = document.getElementById("cancelReportBtn");
                if (existing) existing.remove();
            }

            // ---- show FINALISE only once *all* stages are complete ----
            const allComplete = all4Complete && all5Complete;
            if (allComplete) {
                if (!document.getElementById("finaliseReportBtn")) {
                    const btn = document.createElement("button");
                    btn.id = "finaliseReportBtn";
                    btn.className = "btn btn-sm btn-success mt-4";
                    btn.innerText = "Finalise Report";
                    btn.addEventListener("click", finaliseReport);
                    document.getElementById("completeActions").appendChild(btn);
                }
            } else {
                const existing = document.getElementById("finaliseReportBtn");
                if (existing) existing.remove();
            }

        })
        .catch(err => console.error("Error fetching stage status:", err));
}


const BOARD_ID = '<?$board_id?>'

function finaliseReport() {
    // Fetch the latest data each time the finalise button is clicked
    var master_report_id = MASTER_REPORT_ID; // Assuming this variable is set correctly on the page
    var installationSummary = "";
    var recommendations = "";

    // Use an AJAX call to fetch the current installation data for the master_report_id
    fetch(ROOT_URL + '/includes/elec/getInstallationData.php', {
            method: 'POST',
            body: JSON.stringify({
                master_report_id: master_report_id,
                tenant: TENANT_URL
            }),
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                installationSummary = data.data.installationSummary || '';
                recommendations = data.data.recommendations || '';
            } else {
                // Handle error or fallback if data fetch fails
                console.error('Error fetching installation data');
            }

            // Now that the latest data is fetched, we can proceed with loading the modal content
            var dest = `
        <form id="formComplete">
        <div class="row">
            <input id="board_id" type="hidden" name="board_id" value="<?=htmlspecialchars($board_id, ENT_QUOTES, 'UTF-8')?>">
            <input id="report_id" type="hidden" name="report_id" value="<?=htmlspecialchars($incomplete_report['report_id'] ?? '', ENT_QUOTES, 'UTF-8')?>">
            
            <div class="form-group mb-4 col-12 col-md-6">
                <label class="form-label lead" for="extent">Extent of electrical installation covered by this report</label>
                <input type="text" id="extent" name="installation_details[extent]" class="form-control" value="${data.data.extent || ''}">        
            </div>

            <div class="form-group mb-4 col-12 col-md-3">
                <label class="form-label lead" for="generalCondition">General condition</label>
                <select id="generalCondition" class="form-control md-form" name="generalCondition" >
                    <option value="" disabled selected>Choose your option</option>
                    <option value="SATISFACTORY">SATISFACTORY</option>
                    <option value="UNSATISFACTORY">UNSATISFACTORY</option>
                </select>        
            </div>

            <div class="form-group mb-4">
                <label class="form-label lead" for="installationSummary">Summary of condition</label>
                 <div class="d-flex">
                    <textarea id="installationSummary" name="installationSummary" class="md-textarea form-control" rows="3"></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('installationSummary')">
                            <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','installationSummary','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('installationSummary','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','installationSummary','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('installationSummary')">
                            <i class="fad fa-refresh"></i>
                        </button>
                    </div>
                </div>
            </div>

            <div class="form-group mb-4">
                <label class="form-label lead" for="recommendations">Recommendations</label>
                 <div class="d-flex">

                    <textarea id="recommendations" name="recommendations" class="md-textarea form-control" rows="3"></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('recommendations')">
                            <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','recommendations','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('recommendations','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','recommendations','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('recommendations')">
                            <i class="fad fa-refresh"></i>
                        </button>
                    </div>      
                </div>
            </div>
        </div>
        <div class="row">
            <div class="form-group mb-4 col-12 col-md-4">
                <label class="form-label lead" for="surveyor">Surveyor</label>
                <input type="hidden" class="form-control" name="surveyor" id="surveyor" value="<?= $_SESSION['userid'] ?>" readonly>
                <span class="text-dark"><?= getSurveyorNameForm($_SESSION['userid']) ?></span>
            </div>
        </div>
        <div class="row">
            <div class="form-group mb-4 col-12 col-md-6">
                <label class="form-label lead" for="inspectionDates">Date(s) on which inspection and testing was carried out:</label>
                <input type="text" id="inspectionDates" name="installation_details[inspectionDates]" class="form-control" value="${data.data.inspectionDates || ''}">        
            </div>

            <div class="form-group mb-4 col-12 col-md-6">
                <label class="form-label lead" for="inspectioNextDate">Date on which next inspection and testing should be carried out:</label>
                <input type="date" id="inspectioNextDate" name="inspectioNextDate" class="form-control" value="">        
            </div>
        </div>
        </form>
        `;

            // Now load the modal content
            loadModalContent(dest, "confirmBox", "modal-xl", 1060, "true", "Confirm report complete", "cancelConfirm", saveFinalReport);

            // Reinitialize any MDB components
            document.querySelectorAll('#confirmBox .form-control').forEach(function(selectEl) {
                new mdb.Select(selectEl); // Initialize only within the modal
            });
        })
        .catch(error => {
            console.error('Error fetching data:', error);
        });
}

function saveFinalReport() {
    var form = document.getElementById("formComplete");
    var formData = new FormData(form);

    // Capture the values from the form
    var extent = formData.get('installation_details[extent]');
    var generalCondition = formData.get('generalCondition');
    var installationSummary = formData.get('installationSummary');
    var recommendations = formData.get('recommendations');
    var surveyor = formData.get('surveyor');
    var inspectionDates = formData.get('installation_details[inspectionDates]');
    var inspectioNextDate = formData.get('inspectioNextDate');
    var master_report_id = MASTER_REPORT_ID; // Assuming this is set in the page

    // Prepare the data to send to the server
    var dataToSend = {
        master_report_id: master_report_id,
        extent: extent,
        generalCondition: generalCondition,
        installationSummary: installationSummary,
        recommendations: recommendations,
        surveyor: surveyor,
        inspectionDates: inspectionDates,
        inspectioNextDate: inspectioNextDate,
        tenant: TENANT_URL
    };

    // Send the data to the server for processing
    fetch(ROOT_URL + '/includes/elec/finalise_report.php', {
            method: 'POST',
            body: JSON.stringify(dataToSend), // Send data as JSON
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // If successful, redirect back to the main page
                window.location.href = "index.php?t=includes/master&p=elec.php&clientnumber=1&view=elec_client";
            } else {
                alert('Error finalizing the report: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
}


function updateStageState(stage, status) {
    let formData = new URLSearchParams();
    formData.append("master_report_id", MASTER_REPORT_ID || "");
    formData.append("stage", stage);
    formData.append("status", status);
    formData.append("tenant", TENANT_URL);
    formData.append("is_update", is_update);
    fetch(`${ROOT_URL}/includes/elec/update_stage_status.php`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: formData.toString()
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                updateStageStatus(stage, 'pending');
                checkStageCompletion();

            } else {
                console.error('Error updating stage:', data.message);
            }
        })
        .catch(error => console.error('Error updating stage:', error));
}

// After saving the report and getting the master_report_id:
function saveReportStage(stage) {
    let formData = new FormData();
    formData.append("stage", `save_stage_${stage}`);
    formData.append("board_list", document.getElementById("board_list").value);
    formData.append("tenant", TENANT_URL);
    formData.append("clientnumber", 1); // Replace 1 with your dynamic client number if needed.
    formData.append("is_update", is_update); // Pass is_update to indicate update mode
    formData.append("master_report_id", MASTER_REPORT_ID); // Pass the master_report_id (if available)

    let formElement;
    switch (stage) {
        case 1:
            formElement = document.getElementById("installationDetailsForm");
            break;
        case 2:
            formElement = document.getElementById("scheduleOfInspectionForm");
            break;
        case 3:
            formElement = document.getElementById("conditionReportForm");
            break;
        case 4:
            formElement = document.getElementById("observationsForm");
            break;
        case 5:
            formElement = document.getElementById("circuitInspectionForm");
            break;
        default:
            console.error("Invalid stage: " + stage);
            return;
    }

    // Append all form data
    let inputs = formElement.querySelectorAll("input, select, textarea");
    inputs.forEach(input => {
        if (input.type === "radio") {
            if (input.checked) {
                formData.append(input.name, input.value);
            }
        } else if (input.type === "checkbox") {
            formData.append(input.name, input.checked ? 1 : 0);
        } else {
            formData.append(input.name, input.value);
        }
    });

    fetch(`${ROOT_URL}/includes/elec/load_stage.php?tenant=${TENANT_URL}`, {
            method: "POST",
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                if (data.master_report_id) {
                    // Update MASTER_REPORT_ID if a new report is created or existing report is updated
                    MASTER_REPORT_ID = data.master_report_id;

                    // Set is_update flag to true since we are now updating the report
                    is_update = true;

                    // Log the updated values (for debugging purposes)
                    console.log("Updated MASTER_REPORT_ID:", MASTER_REPORT_ID);
                    console.log("Updated is_update:", is_update);

                    // Optionally, trigger actions here after the update
                    handleReportUpdate();
                }
                killModal('confirmBox');
                showResponse("success", data.message);
                updateStageStatus(stage, 'pending');
                updateStageState(stage, "pending");
                checkStageCompletion();
                checkAllStagesComplete()
                document.getElementById("stageContent").innerHTML = `
                    <div id="landingMessage" class="d-flex flex-column align-items-center justify-content-center my-5">
                        <span class="fa-stack fa-4x">
                            <i class="fad fa-square fa-stack-2x text-primary"></i>
                            <i class="fad fa-bolt fa-stack-1x fa-inverse"></i>
                        </span>
                        <h2 class="mt-3 text-primary">Electrical Inspection Report</h2>
                        <p class="text-muted">Select a stage from the checklist to begin your inspection.</p>
                    </div>`;
            } else {
                showResponse("danger", data.message);
            }
        })
        .catch(error => {
            console.error("Save error:", error);
            showResponse("danger", "Failed to save data.");
        });
}

function saveCircuitStage5(board_id) {
    let formData = new FormData();
    formData.append("stage", "save_stage_5");
    formData.append("board_list", document.getElementById("board_list").value);
    formData.append("tenant", TENANT_URL);
    formData.append("clientnumber", 1); // Replace 1 with your dynamic client number if needed.
    formData.append("is_update", is_update); // Pass is_update to indicate update mode
    formData.append("master_report_id", MASTER_REPORT_ID); // Pass the master_report_id (if available)
    formData.append("board_id", board_id); // Pass the specific board_id for this stage

    // Get the form element for this stage
    let formElement = document.getElementById("circuitInspectionForm");

    // Append all form data (input values) from the form
    let inputs = formElement.querySelectorAll("input, select, textarea");
    inputs.forEach(input => {
        if (input.type === "radio") {
            if (input.checked) {
                formData.append(input.name, input.value);
            }
        } else if (input.type === "checkbox") {
            formData.append(input.name, input.checked ? 1 : 0);
        } else {
            formData.append(input.name, input.value);
        }
    });

    // Send the form data to the server
    fetch(`${ROOT_URL}/includes/elec/load_stage.php?tenant=${TENANT_URL}`, {
            method: "POST",
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                if (data.master_report_id) {
                    // Update MASTER_REPORT_ID if a new report is created or existing report is updated
                    MASTER_REPORT_ID = data.master_report_id;

                    // Set is_update flag to true since we are now updating the report
                    is_update = true;

                    // Log the updated values (for debugging purposes)
                    console.log("Updated MASTER_REPORT_ID:", MASTER_REPORT_ID);
                    console.log("Updated is_update:", is_update);

                    // Optionally, trigger actions here after the update
                    handleReportUpdate();
                }

                killModal('confirmBox');
                showResponse("success", data.message);
                updateStageStatus(5, 'pending');
                updateStageState(5, "pending");
                checkStageCompletion();
                checkAllStagesComplete()
                document.getElementById("stageContent").innerHTML = `
                <div id="landingMessage" class="d-flex flex-column align-items-center justify-content-center my-5">
                    <span class="fa-stack fa-4x">
                        <i class="fad fa-square fa-stack-2x text-primary"></i>
                        <i class="fad fa-bolt fa-stack-1x fa-inverse"></i>
                    </span>
                    <h2 class="mt-3 text-primary">Electrical Inspection Report</h2>
                    <p class="text-muted">Select a stage from the checklist to begin your inspection.</p>
                </div>`;
            } else {
                showResponse("danger", data.message);
            }
        })
        .catch(error => {
            console.error("Save error:", error);
            showResponse("danger", "Failed to save data.");
        });
}

// Function to handle post-update actions
function handleReportUpdate() {
    // Example of what to do after the update
    // You can perform operations like enabling or disabling form fields, changing UI, etc.
    if (is_update) {
        // Logic when it is an update
        console.log("Handling update logic.");
    } else {
        // Logic when it's a new report
        console.log("Handling new report logic.");
    }
}

function markStageComplete(stage) {
    console.log("markStageComplete - stage:", stage, "master_report_id:", MASTER_REPORT_ID);
    updateStageState(stage, 'complete');

    // Prepare form data to send to the backend
    let formData = new URLSearchParams();
    formData.append("tenant", TENANT_URL);
    formData.append("stage", stage);
    formData.append("status", 'complete');
    formData.append("is_update", is_update); // Pass the update flag
    formData.append("master_report_id", MASTER_REPORT_ID); // Pass the master_report_id

    // Sending the data to the backend for update
    fetch(`${ROOT_URL}/includes/elec/update_stage_complete.php`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: formData.toString()
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showResponse("success", `Stage ${stage} marked as complete.`)
                killModal('confirmBox');
                checkStageCompletion();
                checkAllStagesComplete()
                document.getElementById("stageContent").innerHTML = `
        <div id="landingMessage" class="d-flex flex-column align-items-center justify-content-center my-5">
            <span class="fa-stack fa-4x">
                <i class="fad fa-square fa-stack-2x text-primary"></i>
                <i class="fad fa-bolt fa-stack-1x fa-inverse"></i>
            </span>
            <h2 class="mt-3 text-primary">Electrical Inspection Report</h2>
            <p class="text-muted">Select a stage from the checklist to begin your inspection.</p>
        </div>`;

            } else {
                showResponse("error", `Error marking stage complete:, ${data.message}`);
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });

}

// Function to mark stage 4 as complete for a specific board
function markStageComplete5(boardId) {

    // Update the stage 4 for a specific board to 'complete'
    updateStage5Status(boardId, 'complete');

    // Prepare form data to send to the backend
    let formData = new URLSearchParams();
    formData.append("tenant", TENANT_URL);
    formData.append("stage", 5); // Stage 4
    formData.append("status", 'complete'); // Set status as complete
    formData.append("board_id", boardId); // Pass the board ID
    formData.append("master_report_id", MASTER_REPORT_ID); // Pass the master report ID

    // Sending the data to the backend for update
    fetch(`${ROOT_URL}/includes/elec/update_stage_complete.php`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: formData.toString()
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showResponse('success', `Stage 5 for board ${boardId} marked as complete.`);
                killModal('confirmBox');
                checkStageCompletion();
                checkAllStagesComplete()
                document.getElementById("stageContent").innerHTML = `
        <div id="landingMessage" class="d-flex flex-column align-items-center justify-content-center my-5">
            <span class="fa-stack fa-4x">
                <i class="fad fa-square fa-stack-2x text-primary"></i>
                <i class="fad fa-bolt fa-stack-1x fa-inverse"></i>
            </span>
            <h2 class="mt-3 text-primary">Electrical Inspection Report</h2>
            <p class="text-muted">Select a stage from the checklist to begin your inspection.</p>
        </div>`;
            } else {
                showResponse('danger', `Error marking Stage 4 complete for board ${boardId}:, ${data.message}`);
            }
        })
        .catch(error => {
            console.error(`Error marking Stage 4 complete for board ${boardId}:`, error);
        });
}

// General clearStage function for stages 1-3
function clearStage(stage) {
    let formData = new URLSearchParams();
    formData.append("master_report_id", MASTER_REPORT_ID);
    formData.append("stage", stage);
    formData.append("tenant", TENANT_URL);

    fetch(`${ROOT_URL}/includes/elec/clear_stage.php`, {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            body: formData.toString()
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                killModal('confirmBox');
                updateStageState(stage, "empty"); // Immediately set stage status to 'empty'
                checkStageCompletion(); // Re-check the stage completion for all stages
                checkAllStagesComplete()
                document.getElementById("stageContent").innerHTML = `
        <div id="landingMessage" class="d-flex flex-column align-items-center justify-content-center my-5">
            <span class="fa-stack fa-4x">
                <i class="fad fa-square fa-stack-2x text-primary"></i>
                <i class="fad fa-bolt fa-stack-1x fa-inverse"></i>
            </span>
            <h2 class="mt-3 text-primary">Electrical Inspection Report</h2>
            <p class="text-muted">Select a stage from the checklist to begin your inspection.</p>
        </div>`;
                showResponse("success", `Stage ${stage} data cleared`);
            } else {
                console.error("Error clearing stage:", data.message);
            }
        })
        .catch(error => console.error("Error clearing stage:", error));
}


// Clear data for a specific board in stage 4
function clearStage5(boardId) {
    let formData = new URLSearchParams();
    formData.append("master_report_id", MASTER_REPORT_ID);
    formData.append("stage", 5); // Stage 4
    formData.append("board_id", boardId); // Specify the board to clear
    formData.append("tenant", TENANT_URL);

    fetch(`${ROOT_URL}/includes/elec/clear_stage.php`, {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            body: formData.toString()
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                killModal('confirmBox');
                updateStage5Status(boardId, "empty"); // Update status for this board as 'empty'
                checkStageCompletion(); // Re-check the stage completion for all stages
                checkAllStagesComplete()
                //console.log(`Stage 4 data cleared for board ID: ${boardId}`);              
                showResponse("success", `Stage 5 data cleared for board ID: ${boardId}`);
                document.getElementById("stageContent").innerHTML = `
        <div id="landingMessage" class="d-flex flex-column align-items-center justify-content-center my-5">
            <span class="fa-stack fa-4x">
                <i class="fad fa-square fa-stack-2x text-primary"></i>
                <i class="fad fa-bolt fa-stack-1x fa-inverse"></i>
            </span>
            <h2 class="mt-3 text-primary">Electrical Inspection Report</h2>
            <p class="text-muted">Select a stage from the checklist to begin your inspection.</p>
        </div>`;
            } else {
                console.error("Error clearing stage 5 data:", data.message);
            }
        })
        .catch(error => console.error("Error clearing stage 5 data:", error));
}


function cancelReport() {
    // Disable the button to prevent multiple clicks while the process is running
    const cancelBtn = document.getElementById("cancelReportBtn");
    cancelBtn.disabled = true;
    cancelBtn.innerHTML = "<i class='fad fa-spinner-third fa-spin'></i> Cancelling...";

    // Fetch the master_report_id
    const masterReportId = MASTER_REPORT_ID; // Define how to retrieve this, e.g. from URL or hidden input field

    // Send AJAX request to cancel the report (delete rows and images)
    fetch(`${ROOT_URL}/includes/elec/cancel_report.php`, {
            method: 'POST',
            body: new URLSearchParams({
                'master_report_id': masterReportId,
                'tenant': TENANT_URL
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Show success message and reset buttons/content
                showResponse('success', 'Report Cancelled<br>The report and all associated data have been deleted successfully.', () => {
                    // Optionally, redirect or update the UI to reflect the cancellation
                    window.location.href = 'index.php?t=includes/master&p=elec.php&clientnumber=1&view=elec_client'; // Or any other action
                });
            } else {
                // Show error message
                showResponse('danger', 'Failed to cancel the report. Please try again later.');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showResponse('danger', 'An unexpected error occurred while cancelling the report.');
        })
        .finally(() => {
            // Enable the cancel button again after the process is complete
            cancelBtn.disabled = false;
            cancelBtn.innerHTML = "<i class='fad fa-trash-xmark me-1'></i> Cancel";
        });
}


var currentPage = 1;

function showCircuitPage(page) {
    var container = document.getElementById('circuitContainer');
    var direction = null;
    if (page > currentPage) {
        direction = 'right';
    } else if (page < currentPage) {
        direction = 'left';
    }

    if (direction) {
        // Animate the container sliding out.
        container.style.transition = 'transform 0.4s ease';
        // If moving to a higher page, slide left (i.e. content moves left).
        // If moving to a lower page, slide right.
        container.style.transform = (direction === 'right') ? 'translateX(-100%)' : 'translateX(100%)';

        // After the slide-out, update the visible cards and slide the container back in.
        setTimeout(function() {
            // Hide all cards.
            document.querySelectorAll('.circuit-card').forEach(function(card) {
                card.style.display = 'none';
            });
            // Show only the cards that belong to the requested page.
            document.querySelectorAll('.circuit-card[data-page="' + page + '"]').forEach(function(card) {
                card.style.display = 'block';

            });

            // Immediately reset the container position offscreen (from the opposite side).
            container.style.transition = 'none';
            container.style.transform = (direction === 'right') ? 'translateX(100%)' : 'translateX(-100%)';

            // Force a reflow so the browser registers the change.
            container.offsetHeight;

            // Animate the container sliding in to its normal position.
            container.style.transition = 'transform 0.4s ease';
            container.style.transform = 'translateX(0)';

            // Update the current page value.
            currentPage = page;
            initSlimForVisibleCircuits;
            // Update the pagination active state.
            document.querySelectorAll('.pagination .page-item').forEach(function(li) {
                li.classList.remove('active');
            });
            var activeLink = document.querySelector('.pagination .page-item a[onclick*="showCircuitPage(' + page + ')"]');
            if (activeLink && activeLink.parentElement) {
                activeLink.parentElement.classList.add('active');
            }
        }, 400); // Matches the slide-out duration (400ms)
    } else {
        // If no direction (i.e. page is the same), simply update the active pagination link.
        document.querySelectorAll('.pagination .page-item').forEach(function(li) {
            li.classList.remove('active');

        });
        var activeLink = document.querySelector('.pagination .page-item a[onclick*="showCircuitPage(' + page + ')"]');
        if (activeLink && activeLink.parentElement) {
            activeLink.parentElement.classList.add('active');
        }
    }
}

function addInstrumentRow() {
    let table = document.getElementById("instrumentRows");
    let rowCount = table.rows.length;
    let row = table.insertRow();

    row.innerHTML = '<td><input type="text" name="instrument[]" class="form-control" placeholder="Instrument"></td>' +
        '<td><input type="text" name="maker[]" class="form-control" placeholder="Maker"></td>' +
        '<td><input type="text" name="serial_no[]" class="form-control" placeholder="Serial No"></td>' +
        '<td><input type="date" name="last_calibration[]" class="form-control"></td>' +
        '<td><input type="date" name="next_calibration[]" class="form-control"></td>' +
        ' <td class="text-center">' +
        '<button type="button" class="btn btn-outline-danger btn-sm removeInstrumentRow">' +
        '<i class="fad fa-trash-alt"></i>' +
        ' </button>' +
        ' </td>';
    updateInstrumentRowIcons();
}
// Update instrument row icons (handle first row separately)
function updateInstrumentRowIcons() {
    let rows = document.querySelectorAll("#instrumentRows tr");
    rows.forEach((row, index) => {
        let actionCell = row.querySelector("td:last-child");
        if (!actionCell) {
            actionCell = document.createElement("td");
            actionCell.className = "text-center";
            row.appendChild(actionCell);
        }

        if (index === 0) {
            actionCell.innerHTML =
                '<button type="button" class="btn btn-outline-warning btn-sm clearInstrumentRow">' +
                '<i class="fad fa-broom"></i>' +
                '</button>';
        } else {
            actionCell.innerHTML =
                '<button type="button" class="btn btn-outline-danger btn-sm removeInstrumentRow">' +
                '<i class="fad fa-trash-alt"></i>' +
                '</button>';
        }
    });

    attachInstrumentRowEvents();
}

// Attach event listeners for dynamically added rows
function attachInstrumentRowEvents() {
    document.querySelectorAll(".removeInstrumentRow").forEach(button => {
        button.onclick = function() {
            this.closest("tr").remove();
            updateInstrumentRowIcons();
        };
    });

    document.querySelectorAll(".clearInstrumentRow").forEach(button => {
        button.onclick = function() {
            let row = this.closest("tr");
            row.querySelectorAll("input").forEach(input => input.value = "");
        };
    });
}

document.addEventListener("DOMContentLoaded", () => {
    checkStageCompletion();
    updateInstrumentRowIcons();
    checkAllStagesComplete()
});
document.addEventListener("DOMContentLoaded", updateInstrumentRowIcons);
</script>
<?php if ($circuitsCount === 0): ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    var stageContent = document.getElementById('stageContent');
    if (stageContent) {
        stageContent.innerHTML =
            '<div id="landingMessage" class="d-flex flex-column align-items-center justify-content-center my-5">' +
            '<span class="fa-stack fa-4x">' +
            '<i class="fad fa-square fa-stack-2x text-dark"></i>' +
            '<i class="fad fa-bolt fa-stack-1x text-light fa-inverse"></i>' +
            '</span>' +
            '<h2 class="mt-3 text-primary">Electrical Inspection Report</h2>' +
            '<p class="text-muted">Select a stage from the checklist to begin your inspection.</p>' +
            '<div class="alert alert-warning mt-3">No circuits detected. Please <a href="index.php?t=includes/master&p=elec.php&view=elec_new_circuit&data=<?= $d[0]?>|<?= $d[1]?>|<?= $d[2]?>" class="alert-link">define at least one circuit</a>.' +
            '</div>' +
            '</div>';
    }
    var stageItems = document.querySelectorAll('#reportChecklist li');
    stageItems.forEach(function(li) {
        li.classList.add('disabled');
        li.style.pointerEvents = 'none';
        li.style.opacity = '0.6';
    });
});
</script>
<?php endif; ?>