<?php
// lazy_load_circuits.php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (file_exists('../../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../../' . $_REQUEST['tenant'] . '/config.php');
} elseif (file_exists('/config.php')) {
    require_once('/config.php');
} else {
    die("Configuration file not found.");
}

$board_id = isset($_GET['board_id']) ? intval($_GET['board_id']) : 0;
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;

if (!$board_id || $page < 1) {
    die("Invalid request.");
}

// Set the number of circuits per page (3 in this case)
$circuits_per_page = 3;
$offset = ($page - 1) * $circuits_per_page;

// First, count the total circuits for pagination
$count_query = "SELECT COUNT(*) as total FROM elec_circuit WHERE board_id = ?";
$count_stmt = $con->prepare($count_query);
$count_stmt->bind_param("i", $board_id);
$count_stmt->execute();
$count_result = $count_stmt->get_result();
$count_row = $count_result->fetch_assoc();
$totalCircuits = $count_row['total'];
$count_stmt->close();

$totalPages = ($totalCircuits > 0) ? ceil($totalCircuits / $circuits_per_page) : 1;

// Fetch the circuit records for this page
$query = "SELECT circuit_no, circuit_description, circuit_id 
          FROM elec_circuit 
          WHERE board_id = ? 
          ORDER BY circuit_no ASC 
          LIMIT ?, ?";
$stmt = $con->prepare($query);
$stmt->bind_param("iii", $board_id, $offset, $circuits_per_page);
$stmt->execute();
$result = $stmt->get_result();

// We'll use default (blank) values for each circuit's form fields.
// (If you have saved report data, you can merge it here.)
$default = [
    'r1'               => '',
    'rn'               => '',
    'r2'               => '',
    'r1_r2'            => '',
    'r2_continuity'    => '',
    'pp'               => '',
    'pe'               => '',
    'polarity'         => 0,
    'zs'               => '',
    'earth_leakage'    => '',
    'rcd_trip_time'    => '',
    'rcd_functional'   => 0,
    'afdd_functional'  => 0,
    'observations'     => ''
];

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $circuit_no = htmlspecialchars($row['circuit_no']);
        $circuit_description = htmlspecialchars($row['circuit_description']);
        $circuit_id = $row['circuit_id'];

        echo '<div class="card mb-3" id="circuit-' . htmlspecialchars($circuit_id, ENT_QUOTES, 'UTF-8') . '">';
            echo '<div class="card-header bg-light">';
                echo "<h5 class='mb-0'>Circuit $circuit_no: $circuit_description</h5>";
            echo '</div>';
            echo '<div class="card-body">';
            
                // First row: Four columns
                echo '<div class="row">';
                    // Column 1: Continuity Section
                    echo '<div class="col-lg-3">';
                        echo '<h6 class="text-primary">Continuity</h6>';
                        echo '<div class="mb-2"><label>r1 (Ω)</label>';
                        echo "<input type='text' class='form-control form-control-sm' name='circuit_results[$circuit_id][r1]' value='" . htmlspecialchars($default['r1'], ENT_QUOTES, 'UTF-8') . "' required></div>";
                        
                        echo '<div class="mb-2"><label>rn (Ω)</label>';
                        echo "<input type='text' class='form-control form-control-sm' name='circuit_results[$circuit_id][rn]' value='" . htmlspecialchars($default['rn'], ENT_QUOTES, 'UTF-8') . "' required></div>";
                        
                        echo '<div class="mb-2"><label>r2 (Ω)</label>';
                        echo "<input type='text' class='form-control form-control-sm' name='circuit_results[$circuit_id][r2]' value='" . htmlspecialchars($default['r2'], ENT_QUOTES, 'UTF-8') . "' required></div>";
                        
                        echo '<div class="mb-2"><label>R1+R2 (Ω)</label>';
                        echo "<input type='text' class='form-control form-control-sm' name='circuit_results[$circuit_id][r1_r2]' value='" . htmlspecialchars($default['r1_r2'], ENT_QUOTES, 'UTF-8') . "' required></div>";
                        
                        echo '<div class="mb-2"><label>R2 (Ω)</label>';
                        echo "<input type='text' class='form-control form-control-sm' name='circuit_results[$circuit_id][r2_continuity]' value='" . htmlspecialchars($default['r2_continuity'], ENT_QUOTES, 'UTF-8') . "' required></div>";
                    echo '</div>'; // End Column 1
                    
                    // Column 2: Insulation Resistance Section
                    echo '<div class="col-lg-3">';
                        echo '<h6 class="text-primary">Insulation Resistance</h6>';
                        echo '<div class="mb-2"><label>P/P (MΩ)</label>';
                        echo "<input type='text' class='form-control form-control-sm' name='circuit_results[$circuit_id][pp]' value='" . htmlspecialchars($default['pp'], ENT_QUOTES, 'UTF-8') . "' required></div>";
                        
                        echo '<div class="mb-2"><label>P/E (MΩ)</label>';
                        echo "<input type='text' class='form-control form-control-sm' name='circuit_results[$circuit_id][pe]' value='" . htmlspecialchars($default['pe'], ENT_QUOTES, 'UTF-8') . "' required></div>";
                    echo '</div>'; // End Column 2
                    
                    // Column 3: Polarity, Measured Zs, Earth Leakage
                    echo '<div class="col-lg-3">';
                        echo '<h6 class="text-primary">Polarity</h6>';
                        echo '<div class="mb-2"><label>Polarity Confirmed</label><br>';
                        $checked = ($default['polarity'] == 1) ? 'checked' : '';
                        echo "<input type='checkbox' class='form-check-input' name='circuit_results[$circuit_id][polarity]' value='1' $checked></div>";
                        
                        echo '<h6 class="text-primary">Measured Zs</h6>';
                        echo '<div class="mb-2"><label>Zs (Ω)</label>';
                        echo "<input type='text' class='form-control form-control-sm' name='circuit_results[$circuit_id][zs]' value='" . htmlspecialchars($default['zs'], ENT_QUOTES, 'UTF-8') . "' required></div>";
                        
                        echo '<h6 class="text-primary">Earth Leakage</h6>';
                        echo '<div class="mb-2"><label>Earth Leakage (mA)</label>';
                        echo "<input type='text' class='form-control form-control-sm' name='circuit_results[$circuit_id][earth_leakage]' value='" . htmlspecialchars($default['earth_leakage'], ENT_QUOTES, 'UTF-8') . "' required></div>";
                    echo '</div>'; // End Column 3
                    
                    // Column 4: RCD and AFDD
                    echo '<div class="col-lg-3">';
                        echo '<h6 class="text-primary">RCD</h6>';
                        echo '<div class="mb-2"><label>RCD Trip Time (ms)</label>';
                        echo "<input type='text' class='form-control form-control-sm' name='circuit_results[$circuit_id][rcd_trip_time]' value='" . htmlspecialchars($default['rcd_trip_time'], ENT_QUOTES, 'UTF-8') . "' required></div>";
                        
                        echo '<div class="mb-2"><label>RCD Functional Test</label><br>';
                        $checked = ($default['rcd_functional'] == 1) ? 'checked' : '';
                        echo "<input type='checkbox' class='form-check-input' name='circuit_results[$circuit_id][rcd_functional]' value='1' $checked></div>";
                        
                        echo '<h6 class="text-primary">AFDD</h6>';
                        echo '<div class="mb-2"><label>AFDD Functional Test</label><br>';
                        $checked = ($default['afdd_functional'] == 1) ? 'checked' : '';
                        echo "<input type='checkbox' class='form-check-input' name='circuit_results[$circuit_id][afdd_functional]' value='1' $checked></div>";
                    echo '</div>'; // End Column 4
                echo '</div>'; // End first row
                
                // Additional Details Row (full width)
                echo '<div class="row">';
                    echo '<div class="col-12">';
                        echo '<h6 class="text-primary">Additional Details</h6>';
                        echo '<div class="mb-2"><label>Observations</label>';
                        echo "<textarea class='form-control form-control-sm' name='circuit_results[$circuit_id][observations]' rows='2'>" . htmlspecialchars($default['observations'], ENT_QUOTES, 'UTF-8') . "</textarea></div>";
                        
                        echo '<div class="mb-2"><label>Upload Images</label>';
                        echo '<div class="row">';
                            for ($img = 1; $img <= 6; $img++) {
                                echo '<div class="col-lg-2 col-md-4 col-6 mb-2">';
                                    echo "<input type='file' class='form-control form-control-sm' name='circuit_results[$circuit_id][images][]'>";
                                    echo "<small class='form-text text-muted'>Image $img</small>";
                                echo '</div>';
                            }
                        echo '</div>'; // End images row
                        echo '</div>'; // End Upload Images section
                    echo '</div>'; // End full-width column
                echo '</div>'; // End Additional Details row
                
                // Hidden input for circuit id
                echo "<input type='hidden' name='circuit_results[$circuit_id][circuit_id]' value='" . htmlspecialchars($circuit_id, ENT_QUOTES, 'UTF-8') . "'>";
            echo '</div>'; // End card-body
        echo '</div>'; // End card
    }
} else {
    echo '<p>No circuits found.</p>';
}
$stmt->close();

// Output pagination links if more than one page exists
if ($totalCircuits > $circuits_per_page) {
    echo '<nav aria-label="Circuit results pagination">';
    echo '<ul class="pagination justify-content-center">';
        // Previous page link
        if ($page > 1) {
            $prevPage = $page - 1;
            echo '<li class="page-item"><a class="page-link" href="#" onclick="loadCircuitPage(' . $prevPage . '); return false;">Previous</a></li>';
        } else {
            echo '<li class="page-item disabled"><span class="page-link">Previous</span></li>';
        }
        // Numbered page links
        for ($i = 1; $i <= $totalPages; $i++) {
            $active = ($i == $page) ? 'active' : '';
            echo '<li class="page-item ' . $active . '"><a class="page-link" href="#" onclick="loadCircuitPage(' . $i . '); return false;">' . $i . '</a></li>';
        }
        // Next page link
        if ($page < $totalPages) {
            $nextPage = $page + 1;
            echo '<li class="page-item"><a class="page-link" href="#" onclick="loadCircuitPage(' . $nextPage . '); return false;">Next</a></li>';
        } else {
            echo '<li class="page-item disabled"><span class="page-link">Next</span></li>';
        }
    echo '</ul>';
    echo '</nav>';
}
?>