<?php
// Display a header note
echo '<div class="note note-secondary mb-3"><strong>Schedule of Inspection Report</strong></div>';

// Retrieve existing report data if available
$reportData = null;
if (!empty($incomplete_report['master_report_id'])) {
    $query = "SELECT schedule_of_inspection 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 (flat naming is used)
$scheduleData = !empty($reportData['schedule_of_inspection']) ? json_decode($reportData['schedule_of_inspection'], true) : [];

// Start the form
echo '<form id="scheduleOfInspectionForm">';

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

<!-- =====================================================
     SECTION I. SUPPLY CHARACTERISTICS AND EARTHING ARRANGEMENTS
===================================================== -->
<div class="card mb-4">
    <div class="card-header">
        Supply Characteristics and Earthing Arrangements
    </div>
    <div class="card-body">
        <!-- --------------------------
         Row 1: Earthing Arrangements
         -------------------------- -->
        <div class="row mb-3">
            <div class="col-md-12">
                <h5>Earthing Arrangements</h5>
                <?php
          $earthing_options = ['TN-C', 'TN-S', 'TN-C-S', 'TT', 'IT'];
          $selected_earthing = $scheduleData['earthing_arrangement'] ?? '';
          foreach ($earthing_options as $option) {
              echo '<div class="form-check form-check-inline">';
              echo '<input class="form-check-input" type="radio" name="earthing_arrangement" id="ea_' . $option . '" value="' . $option . '" ' 
                    . ($selected_earthing == $option ? 'checked' : '') . ' required>';
              echo '<label class="form-check-label" for="ea_' . $option . '">' . $option . '</label>';
              echo '</div>';
          }
        ?>
            </div>
        </div>

        <!-- --------------------------
         Row 2: Number and Type of Live Conductors
         -------------------------- -->
        <div class="row mb-3">
            <div class="col-md-12">
                <h5>Number and Type of Live Conductors</h5>
                <!-- System Type: A/C or D/C -->
                <div class="mb-2">
                    <label class="form-label">System Type</label><br>
                    <?php
            $system_type = $scheduleData['system_type'] ?? '';
            echo '<div class="form-check form-check-inline">';
            echo '<input class="form-check-input" type="radio" name="system_type" id="system_ac" value="AC" ' 
                  . ($system_type == 'AC' ? 'checked' : '') . ' required>';
            echo '<label class="form-check-label" for="system_ac">A/C</label>';
            echo '</div>';
            echo '<div class="form-check form-check-inline">';
            echo '<input class="form-check-input" type="radio" name="system_type" id="system_dc" value="DC" ' 
                  . ($system_type == 'DC' ? 'checked' : '') . ' required>';
            echo '<label class="form-check-label" for="system_dc">D/C</label>';
            echo '</div>';
          ?>
                </div>

                <!-- A/C Live Conductor Options -->
                <div class="mb-2">
                    <label class="form-label">A/C Live Conductor Type</label><br>
                    <?php
            $ac_options = [
                "1phase_2wire" => "1‑phase, 2‑wire",
                "2phase_3wire" => "2‑phase, 3‑wire",
                "3phase_3wire" => "3‑phase, 3‑wire",
                "3phase_4wire" => "3‑phase, 4‑wire"
            ];
            $selected_ac = $scheduleData['live_conductors_AC'] ?? '';
            foreach ($ac_options as $key => $label) {
                echo '<div class="form-check form-check-inline">';
                echo '<input class="form-check-input" type="radio" name="live_conductors_AC" id="ac_' . $key . '" value="' . $key . '" ' 
                      . ($selected_ac == $key ? 'checked' : '') . '>';
                echo '<label class="form-check-label" for="ac_' . $key . '">' . $label . '</label>';
                echo '</div>';
            }
          ?>
                </div>

                <!-- D/C Live Conductor Options -->
                <div class="mb-2">
                    <label class="form-label">D/C Live Conductor Type</label><br>
                    <?php
            $dc_options = [
                "2wire" => "2‑wire",
                "3wire" => "3‑wire"
            ];
            $selected_dc = $scheduleData['live_conductors_DC'] ?? '';
            foreach ($dc_options as $key => $label) {
                echo '<div class="form-check form-check-inline">';
                echo '<input class="form-check-input" type="radio" name="live_conductors_DC" id="dc_' . $key . '" value="' . $key . '" ' 
                      . ($selected_dc == $key ? 'checked' : '') . '>';
                echo '<label class="form-check-label" for="dc_' . $key . '">' . $label . '</label>';
                echo '</div>';
            }
          ?>
                </div>

                <!-- Polarity / Phase Sequence Verified Checkbox -->
                <div class="mb-2">
                    <?php $polarity_checked = (!empty($scheduleData['polarity_verified']) && $scheduleData['polarity_verified'] == 1) ? 'checked' : ''; ?>
                    <div class="form-check">
                        <input type="checkbox" class="form-check-input" name="polarity_verified" id="polarity_verified" value="1" <?php echo $polarity_checked; ?>>
                        <label class="form-check-label" for="polarity_verified">Polarity / Phase Sequence Verified</label>
                    </div>
                </div>
            </div>
        </div>

        <!-- --------------------------
         Row 3: Nature of Supply Parameters
         -------------------------- -->
        <div class="row mb-3">
            <h5>Nature of Supply Parameters</h5>
            <div class="col-12 col-md-2 mb-2">
                <label class="form-label">Normal Voltage (U/Uo)</label>
                <input type="text" class="form-control" name="normal_voltage" value="<?php echo htmlspecialchars($scheduleData['normal_voltage'] ?? '', ENT_QUOTES); ?>">
            </div>
            <div class="col-12 col-md-2 mb-2">
                <label class="form-label">Nominal Frequency (f)</label>
                <input type="text" class="form-control" name="nominal_frequency" value="<?php echo htmlspecialchars($scheduleData['nominal_frequency'] ?? '', ENT_QUOTES); ?>">
            </div>
            <div class="col-12 col-md-2 mb-2">
                <label class="form-label">Prospective Fault Current</label>
                <input type="text" class="form-control" name="pfc" value="<?php echo htmlspecialchars($scheduleData['pfc'] ?? '', ENT_QUOTES); ?>">
            </div>
            <div class="col-12 col-md-2 mb-2">
                <label class="form-label">External Loop Impedance (Ze)</label>
                <input type="text" class="form-control" name="ze" value="<?php echo htmlspecialchars($scheduleData['ze'] ?? '', ENT_QUOTES); ?>">
            </div>
            <div class="col-12 col-md-2 mb-2">
                <label class="form-label">Number of Sources</label>
                <input type="text" class="form-control" name="num_sources" value="<?php echo htmlspecialchars($scheduleData['num_sources'] ?? '', ENT_QUOTES); ?>">
            </div>
        </div>

        <div class="row mb-3">
            <div class="col-12 col-md-2 mb-2">
                <label class="form-label">(1) by enquiry (2) by measurement</label>
                <input type="text" class="form-control" name="encMeas" value="<?php echo htmlspecialchars($scheduleData['encMeas'] ?? '', ENT_QUOTES); ?>">
            </div>
        </div>

        <!-- --------------------------
         Row 4: Supply Protective Device
         -------------------------- -->
        <div class="row mb-3">
            <h5>Supply Protective Device</h5>
            <div class="col-12 col-md-4 mb-2">
                <label class="form-label">BS (EN)</label>
                <input type="text" class="form-control" name="protective_device_bs_en" value="<?php echo htmlspecialchars($scheduleData['protective_device_bs_en'] ?? '', ENT_QUOTES); ?>">
            </div>
            <div class="col-12 col-md-4 mb-2">
                <label class="form-label">Type</label>
                <input type="text" class="form-control" name="protective_device_type" value="<?php echo htmlspecialchars($scheduleData['protective_device_type'] ?? '', ENT_QUOTES); ?>">
            </div>
            <div class="col-12 col-md-4 mb-2">
                <label class="form-label">Rating</label>
                <input type="text" class="form-control" name="protective_device_rating" value="<?php echo htmlspecialchars($scheduleData['protective_device_rating'] ?? '', ENT_QUOTES); ?>">
            </div>
        </div>
    </div>
</div>

<!-- =====================================================
     SECTION II. MAIN SWITCH / SWITCH-FUSE / CIRCUIT-BREAKER / RCD
===================================================== -->
<div class="card mb-4">
    <div class="card-header">
        Main Switch / Switch-Fuse / Circuit-Breaker / RCD
    </div>
    <div class="card-body">
        <div class="row mb-3">
            <!-- Location -->
            <div class="col-md-4 mb-2">
                <label class="form-label">Location</label>
                <?php $main_switch_location = $scheduleData['main_switch_location'] ?? ''; ?>
                <input type="text" class="form-control" name="main_switch_location" value="<?php echo htmlspecialchars($main_switch_location, ENT_QUOTES); ?>">
            </div>
            <!-- No. of Poles -->
            <div class="col-md-2 mb-2">
                <label class="form-label">No. of Poles</label>
                <?php $main_switch_poles = $scheduleData['main_switch_poles'] ?? ''; ?>
                <input type="text" class="form-control" name="main_switch_poles" value="<?php echo htmlspecialchars($main_switch_poles, ENT_QUOTES); ?>">
            </div>
            <!-- BS EN -->
            <div class="col-md-2 mb-2">
                <label class="form-label">BS (EN)</label>
                <?php $main_switch_bsen = $scheduleData['main_switch_bsen'] ?? ''; ?>
                <input type="text" class="form-control" name="main_switch_bsen" value="<?php echo htmlspecialchars($main_switch_bsen, ENT_QUOTES); ?>">
            </div>
            <!-- Current Rating -->
            <div class="col-md-2 mb-2">
                <label class="form-label">Current Rating</label>
                <?php $main_switch_current_rating = $scheduleData['main_switch_current_rating'] ?? ''; ?>
                <input type="text" class="form-control" name="main_switch_current_rating" value="<?php echo htmlspecialchars($main_switch_current_rating, ENT_QUOTES); ?>">
            </div>
            <!-- Fuse/Device Rating -->
            <div class="col-md-2 mb-2">
                <label class="form-label">Fuse/Device Rating</label>
                <?php $main_switch_fuse_rating = $scheduleData['main_switch_fuse_rating'] ?? ''; ?>
                <input type="text" class="form-control" name="main_switch_fuse_rating" value="<?php echo htmlspecialchars($main_switch_fuse_rating, ENT_QUOTES); ?>">
            </div>
            <!-- Voltage Rating -->
            <div class="col-md-2 mb-2">
                <label class="form-label">Voltage Rating</label>
                <?php $main_switch_voltage_rating = $scheduleData['main_switch_voltage_rating'] ?? ''; ?>
                <input type="text" class="form-control" name="main_switch_voltage_rating" value="<?php echo htmlspecialchars($main_switch_voltage_rating, ENT_QUOTES); ?>">
            </div>
            <!-- Residual Current -->
            <div class="col-md-2 mb-2">
                <label class="form-label">Rated Residual Operating Current (at 1∆n)</label>
                <?php $main_switch_residual_current = $scheduleData['main_switch_residual_current'] ?? ''; ?>
                <input type="text" class="form-control" name="main_switch_residual_current" value="<?php echo htmlspecialchars($main_switch_residual_current, ENT_QUOTES); ?>">
            </div>
            <!-- Rated Time Delay -->
            <div class="col-md-2 mb-2">
                <label class="form-label">Rated Time Delay</label>
                <?php $main_switch_time_delay = $scheduleData['main_switch_time_delay'] ?? ''; ?>
                <input type="text" class="form-control" name="main_switch_time_delay" value="<?php echo htmlspecialchars($main_switch_time_delay, ENT_QUOTES); ?>">
            </div>
            <!-- Measured Operating Time -->
            <div class="col-md-2 mb-2">
                <label class="form-label">Measured Operating time (at 1∆n)</label>
                <?php $main_switch_operating_time = $scheduleData['main_switch_operating_time'] ?? ''; ?>
                <input type="text" class="form-control" name="main_switch_operating_time" value="<?php echo htmlspecialchars($main_switch_operating_time, ENT_QUOTES); ?>">
            </div>
        </div>
    </div>
</div>

<!-- =====================================================
     SECTION J. PARTICULARS OF INSTALLATION REFERRED TO IN THE REPORT
===================================================== -->
<div class="card mb-4">
    <div class="card-header">
        Particulars of Installation Referred to in the Report
    </div>
    <div class="card-body">
        <h5>Means of Earthing</h5>
        <!-- Distributors Facility -->
        <div class="row mb-3">
            <div class="col-md-2">
                <div class="form-check">
                    <?php $dist_checked = (!empty($scheduleData['distributors_facility_checked']) && $scheduleData['distributors_facility_checked'] == 1) ? 'checked' : ''; 
                    echo '<input type="checkbox" class="form-check-input" name="distributors_facility_checked" value="1" ' . $dist_checked . '>';
                    echo '<label class="form-check-label">Distributors Facility</label>';
                    ?>
                </div>
            </div>
            <div class="col-md-3">
                <label class="form-label">Type</label>
                <?php $dist_type = $scheduleData['distributors_facility_type'] ?? ''; ?>
                <input type="text" class="form-control" name="distributors_facility_type" value="<?php echo htmlspecialchars($dist_type, ENT_QUOTES); ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label">Location</label>
                <?php $dist_location = $scheduleData['distributors_facility_location'] ?? ''; ?>
                <input type="text" class="form-control" name="distributors_facility_location" value="<?php echo htmlspecialchars($dist_location, ENT_QUOTES); ?>">
            </div>
            <div class="col-md-4">
                <label class="form-label">Electrode Resistance</label>
                <?php $dist_resis = $scheduleData['distributors_facility_resistance'] ?? ''; ?>
                <input type="text" class="form-control" name="distributors_facility_resistance" value="<?php echo htmlspecialchars($dist_resis, ENT_QUOTES); ?>">
            </div>
        </div>
        <!-- Installation Earth Electrode -->
        <div class="row mb-3">
            <div class="col-md-4">
                <label class="form-label">Installation Earth Electrode</label>
                <?php $inst_electrode = $scheduleData['installation_electrode_electrode'] ?? ''; ?>
                <input type="text" class="form-control" name="installation_electrode_electrode" value="<?php echo htmlspecialchars($inst_electrode, ENT_QUOTES); ?>">
            </div>
            <div class="col-md-4">
                <label class="form-label">eg rod(s), tape etc</label>
                <?php $inst_electrode_type = $scheduleData['installation_electrode_type'] ?? ''; ?>
                <input type="text" class="form-control" name="installation_electrode_type" value="<?php echo htmlspecialchars($inst_electrode_type, ENT_QUOTES); ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label">Resistance to Earth (ohms)</label>
                <?php $inst_resis = $scheduleData['installation_electrode_resistance'] ?? ''; ?>
                <input type="text" class="form-control" name="installation_electrode_resistance" value="<?php echo htmlspecialchars($inst_resis, ENT_QUOTES); ?>">
            </div>
        </div>
        <!-- Main Protective Conductors -->
        <h5>Main Protective Conductors</h5>
        <div class="row mb-3">
            <div class="col-md-4">
                <label class="form-label">Earthing Conductor Material</label>
                <?php $earthing_material = $scheduleData['earthing_conductor_material'] ?? ''; ?>
                <input type="text" class="form-control" name="earthing_conductor_material" value="<?php echo htmlspecialchars($earthing_material, ENT_QUOTES); ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label">Size</label>
                <?php $earthing_size = $scheduleData['earthing_conductor_size'] ?? ''; ?>
                <input type="text" class="form-control" name="earthing_conductor_size" value="<?php echo htmlspecialchars($earthing_size, ENT_QUOTES); ?>">
            </div>
            <div class="col-md-4">
                <label class="form-label">Connection/Continuity Verified</label><br>
                <input type="checkbox" class="form-check-input" name="earthing_conductor_verified" value="1"
                       <?php echo (!empty($scheduleData['earthing_conductor_verified']) && $scheduleData['earthing_conductor_verified'] == 1) ? 'checked' : ''; ?>>
            </div>
        </div>
        <!-- Main Protective Bonding Conductor -->
        <div class="row mb-3">
            <div class="col-md-4">
                <label class="form-label">Bonding Conductor Material</label>
                <?php $bonding_material = $scheduleData['bonding_conductor_material'] ?? ''; ?>
                <input type="text" class="form-control" name="bonding_conductor_material" value="<?php echo htmlspecialchars($bonding_material, ENT_QUOTES); ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label">Size</label>
                <?php $bonding_size = $scheduleData['bonding_conductor_size'] ?? ''; ?>
                <input type="text" class="form-control" name="bonding_conductor_size" value="<?php echo htmlspecialchars($bonding_size, ENT_QUOTES); ?>">
            </div>
            <div class="col-md-4">
                <label class="form-label">Connection/Continuity Verified</label><br>
                <input type="checkbox" class="form-check-input" name="bonding_conductor_verified" value="1"
                       <?php echo (!empty($scheduleData['bonding_conductor_verified']) && $scheduleData['bonding_conductor_verified'] == 1) ? 'checked' : ''; ?>>
            </div>
        </div>
        <!-- Services -->
        <h5>Services</h5>
        <div class="row mb-3">
            <?php
      $services = [
          'services_water_service'       => 'To incoming Water Service',
          'services_gas_service'         => 'To incoming Gas Service',
          'services_oil_service'         => 'To incoming Oil Service',
          'services_structural_steel'    => 'To structural steel',
          'services_lightning_protection'=> 'To lightning protection',
          'services_other_services'      => 'To other incoming service(s)'
      ];
      foreach ($services as $key => $label) {
          $checked = (!empty($scheduleData[$key]) && $scheduleData[$key] == 1) ? 'checked' : '';
          echo '<div class="col-md-4">';
          echo '<div class="form-check">';
          echo '<input type="checkbox" class="form-check-input" name="' . $key . '" value="1" ' . $checked . '>';
          echo '<label class="form-check-label">' . $label . '</label>';
          echo '</div>';
          echo '</div>';
      }
      ?>
        </div>
    </div>
</div>

<!-- =====================================================
     Form 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?', () => saveReportStage(2))">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?', () => markStageComplete(2))">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?', () => clearStage(2))">Clear all</button>
    </div>
</div>

<?php 
echo '</form>';
?>