<?php
// Retrieve existing report data if available
$reportData = null;
if (!empty($incomplete_report['master_report_id'])) {
    $query = "SELECT condition_schedule, test_instruments FROM elec_report WHERE master_report_id = ?";
    $stmt = $con->prepare($query);
    $stmt->bind_param("s", $incomplete_report['master_report_id']);
    $stmt->execute();
    $result = $stmt->get_result();
    $reportData = $result->fetch_assoc();
    $stmt->close();
}

// Decode JSON stored data (if available)
$conditionReportData = !empty($reportData['condition_schedule']) ? json_decode($reportData['condition_schedule'], true) : [];
$testInstrumentsData = !empty($reportData['test_instruments']) ? json_decode($reportData['test_instruments'], true) : [];

// Start form
echo '<div class="note note-secondary mb-3"><strong>Condition Report Inspection Schedule</strong></div>';
echo '<form id="conditionReportForm">';

// Hidden Fields – now including board_list and locnumber for the new process
echo '<input type="hidden" id="board_id" name="board_id" value="' . htmlspecialchars($board_id, ENT_QUOTES, 'UTF-8') . '">';
echo '<input type="hidden" id="report_id" name="report_id" value="' . htmlspecialchars($incomplete_report['report_id'] ?? '', ENT_QUOTES, 'UTF-8') . '">';
echo '<input type="hidden" id="locnumber" name="locnumber" value="' . htmlspecialchars($locnumber, ENT_QUOTES, 'UTF-8') . '">';
if (isset($ALL_BOARD_LIST)) {
    echo '<input type="hidden" id="board_list" name="board_list" value=\'' . htmlspecialchars(json_encode($ALL_BOARD_LIST, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), ENT_QUOTES, 'UTF-8') . '\'>';
}

echo '<table class="table table-bordered table-striped table-sm">';
echo '<thead class="table-dark">';
echo '<tr>
        <th width="10%">Item No</th>
        <th>Description</th>
        <th width="20%">Outcome</th>
        <th width="15%">Further Investigation</th>
      </tr>';
echo '</thead>';
echo '<tbody>';

// Inspection Schedule Data (All Sections)
$inspection_schedule = [
    "DISTRIBUTOR'S / SUPPLY INTAKE EQUIPMENT" => [
        ['1.0', 'Condition of service cable'],
        ['1.1', 'Condition of service head'],
        ['1.2', 'Condition of distributor’s earthing arrangement'],
        ['1.3', 'Condition of meter tails – Distributor/Consumer'],
        ['1.4', 'Condition of metering equipment'],
        ['1.5', 'Condition of isolator (where present)']
    ],
    "PRESENCE OF ADEQUATE ARRANGEMENTS FOR OTHER SOURCES" => [
        ['2.0', 'Presence of adequate arrangements for microgenerators']
    ],
    "EARTHING / BONDING ARRANGEMENTS" => [
        ['3.1', 'Presence and condition of distributor’s earthing arrangements'],
        ['3.2', 'Presence and condition of earth electrode connection where applicable'],
        ['3.3', 'Provision of earthing / bonding labels at all appropriate locations'],
        ['3.4', 'Confirmation of earthing conductor size'],
        ['3.5', 'Accessibility and condition of earthing conductor at MET'],
        ['3.6', 'Confirmation of main protective bonding conductor sizes']
    ],
    "CONSUMER UNIT(S) / DISTRIBUTION BOARD(S)" => [
        ['4.1', 'Adequacy of working space / accessibility to consumer unit / distribution board'],
        ['4.2', 'Security of fixing'],
        ['4.3', 'Condition of enclosure(s) in terms of IP rating'],
        ['4.4', 'Condition of enclosure(s) in terms of fire rating'],
        ['4.5', 'Enclosure not damaged / deteriorated so as to impair safety'],
        ['4.6', 'Presence of main linked switch'],
        ['4.7', 'Operation of main switch (functional check)'],
        ['4.8', 'Manual operation of circuit breakers and RCDs to prove disconnection'],
        ['4.9', 'Correct identification of circuit details and protective devices'],
        ['4.10', 'Presence of RCD six-monthly test notice at or near consumer unit / distribution board'],
        ['4.11', 'Presence of alternative supply warning notice at or near consumer unit / distribution board'],
        ['4.12', 'Presence of other required labelling'],
        ['4.13', 'Compatibility of protective devices, bases and other components'],
        ['4.14', 'Single-pole protective devices in line conductor only'],
        ['4.15', 'Protection against mechanical damage where cables enter consumer unit / distribution board']
    ],
    "FINAL CIRCUITS" => [
        ['5.1', 'Identification of conductors'],
        ['5.2', 'Cables correctly supported throughout their run'],
        ['5.3', 'Condition of insulation of live parts'],
        ['5.4', 'Non-sheathed cables protected by enclosure in conduit, ducting or trunking'],
        ['5.5', 'Condition of insulation of live parts'],
        ['5.6', 'Condition of insulation of live parts'],
        ['5.7', 'Condition of insulation of live parts']
    ],
    "LOCATIONS CONTAINING A BATH OR SHOWER" => [
        ['6.1', 'Additional protection for all low voltage (LV) circuits by RCD not exceeding 30mA'],
        ['6.2', 'Where used as a protective measure, requirements for SELV or PELV met'],
        ['6.3', 'Shaver sockets comply with BS EN 61558-2-5'],
        ['6.4', 'Presence of supplementary bonding conductors'],
        ['6.5', 'Low voltage (e.g. 230 volt) socket-outlets sited at least 3m from zone 1'],
        ['6.6', 'Suitability of equipment for external influences for installed location'],
        ['6.7', 'Suitability of current-using equipment for particular position within the location']
    ],
    "OTHER PART 7 SPECIAL INSTALLATIONS OR LOCATIONS" => [
        ['7.1', 'List all other special installations or locations present, if any']
    ],
    "PROSUMER’S LOW VOLTAGE ELECTRICAL INSTALLATIONS" => [
        ['8.1', 'Where the installation includes additional requirements and recommendations relating to Chapter 82']
    ]
];

// Loop through each section and populate the form
foreach ($inspection_schedule as $section => $rows) {
    echo '<tr class="table-secondary"><td colspan="4"><strong>' . htmlspecialchars($section) . '</strong></td></tr>';
    
    foreach ($rows as $row) {
        $item_number = $row[0];
        $description = $row[1];

        // Retrieve saved values for this item
        $savedOutcome = $conditionReportData[$item_number]['outcome'] ?? '';
        $furtherInvestigationChecked = isset($conditionReportData[$item_number]['further_investigation']) && $conditionReportData[$item_number]['further_investigation'] == 1 ? 'checked' : '';

        echo '<tr>';
        echo '<td>' . htmlspecialchars($item_number) . '</td>';
        echo '<td>' . htmlspecialchars($description) . '</td>';
        echo '<td>
                <select class="form-select" name="outcome[' . htmlspecialchars($item_number) . ']">
                    <option value="">Select</option>
                    <option value="✔" ' . ($savedOutcome == "✔" ? 'selected' : '') . '>✔</option>
                    <option value="C1" ' . ($savedOutcome == "C1" ? 'selected' : '') . '>C1</option>
                    <option value="C2" ' . ($savedOutcome == "C2" ? 'selected' : '') . '>C2</option>
                    <option value="C3" ' . ($savedOutcome == "C3" ? 'selected' : '') . '>C3</option>
                </select>
              </td>';
        echo '<td><input type="checkbox" name="further_investigation[' . htmlspecialchars($item_number) . ']" value="1" ' . $furtherInvestigationChecked . '></td>';
        echo '</tr>';
    }
}

echo '</tbody>';
echo '</table>';

// **Details of Test Instruments Used Section**
echo '<h4 class="text-info mt-4">Details of Test Instruments Used</h4>';
echo '<table class="table table-bordered table-striped table-sm">';
echo '<thead class="table-dark">';
echo '<tr>
        <th>Instrument</th>
        <th>Maker</th>
        <th>Serial No</th>
        <th>Last Calibration Date</th>
        <th>Next Calibration Date</th>
        <th></th>
      </tr>';
echo '</thead>';
echo '<tbody id="instrumentRows">';

// **Retrieve saved instruments (if any)**
if (!empty($testInstrumentsData)) {
    $rowIndex = 0;
    foreach ($testInstrumentsData as $instrument) {
        echo '<tr>
                <td><input type="text" name="instrument[]" class="form-control" value="' . htmlspecialchars($instrument['instrument'] ?? '') . '" placeholder="Instrument"></td>
                <td><input type="text" name="maker[]" class="form-control" value="' . htmlspecialchars($instrument['maker'] ?? '') . '" placeholder="Maker"></td>
                <td><input type="text" name="serial_no[]" class="form-control" value="' . htmlspecialchars($instrument['serial_no'] ?? '') . '" placeholder="Serial No"></td>
                <td><input type="date" name="last_calibration[]" class="form-control" value="' . htmlspecialchars($instrument['last_calibration'] ?? '') . '"></td>
                <td><input type="date" name="next_calibration[]" class="form-control" value="' . htmlspecialchars($instrument['next_calibration'] ?? '') . '"></td>
                <td class="text-center">';
        if ($rowIndex === 0) {
            echo '<button type="button" class="btn btn-outline-warning btn-sm clearInstrumentRow">
                    <i class="fad fa-broom"></i>
                  </button>';
        } else {
            echo '<button type="button" class="btn btn-outline-danger btn-sm removeInstrumentRow">
                    <i class="fad fa-trash-alt"></i>
                  </button>';
        }
        echo '</td></tr>';
        $rowIndex++;
    }
} else {
    // No saved data: display one empty row with a clear button
    echo '<tr>
            <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-warning btn-sm clearInstrumentRow">
                    <i class="fad fa-broom"></i>
                </button>
            </td>
          </tr>';
}

echo '</tbody>';
echo '</table>';
echo '<button type="button" class="btn btn-secondary" onclick="addInstrumentRow()">Add Instrument</button>';

// Form Buttons
echo '<div class="d-flex justify-content-between align-items-center mt-4">';
    echo '<button type="button" class="btn btn-success" onclick="alertMessage(\'Confirm Save\', \'Are you sure you want to save this stage?\', () => saveReportStage(3))">Save Progress</button>';
    echo '<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?\', () => markStageComplete(3))">Mark Complete</button>';
    echo '<button id="clearStageBtn" type="button" class="btn btn-danger" onclick="alertMessage(\'Confirm Clear\', \'This will reset all data for this stage. Are you sure?\', () => clearStage(3))">Clear all</button>';
echo '</div>';

echo '</form>';
?>