<?php
// fetch_board_circuits.php
header('Content-Type: application/json; charset=utf-8');

// 1) Load config
if (file_exists('../../../' . $_POST['tenant'] . '/config.php')) {
    require_once('../../../' . $_POST['tenant'] . '/config.php');
} elseif (file_exists('/config.php')) {
    require_once('/config.php');
} else {
    die(json_encode(['success' => false, 'message' => 'Configuration file not found.']));
}

// 2) Validate board_id
$board_id = isset($_POST['board_id']) ? intval($_POST['board_id']) : 0;
if (!$board_id) {
    die(json_encode(['success' => false, 'message' => 'Board ID is missing.']));
}

try {
    // 3) Fetch the board's mode
    $bm = $con->prepare("SELECT circuit_mode FROM elec_board WHERE board_id = ?");
    $bm->bind_param("i", $board_id);
    $bm->execute();
    $bm_row = $bm->get_result()->fetch_assoc() ?: ['circuit_mode'=>'LV'];
    $mode = $bm_row['circuit_mode'];
    $bm->close();

    // 4) Pull each circuit’s JSON parts
    $sql = "
        SELECT 
            circuit_id,
            base_circuit_no,
            parts
        FROM elec_circuit
        WHERE board_id = ?
        ORDER BY CAST(base_circuit_no AS UNSIGNED) ASC
    ";
    $stmt = $con->prepare($sql);
    $stmt->bind_param('i', $board_id);
    $stmt->execute();
    $result = $stmt->get_result();

    $circuits = [];
    while ($row = $result->fetch_assoc()) {
        $parts = json_decode($row['parts'], true) ?: [];

        if ($mode === 'LV') {
            // === original 3-spur table layout ===
            $l1 = $l2 = $l3 = '-';
            foreach ($parts as $p) {
                switch ($p['label']) {
                    case 'L1': $l1 = $p['circuit_description']; break;
                    case 'L2': $l2 = $p['circuit_description']; break;
                    case 'L3': $l3 = $p['circuit_description']; break;
                }
            }

            $desc = '<table width="100%"><tr>'
                  . '<td width="33%"><span class="badge" style="background-color:brown">L1:</span> '
                    . htmlspecialchars($l1) . '</td>'
                  . '<td width="33%"><span class="badge" style="background-color:black">L2:</span> '
                    . htmlspecialchars($l2) . '</td>'
                  . '<td width="33%"><span class="badge" style="background-color:grey">L3:</span> '
                    . htmlspecialchars($l3) . '</td>'
                  . '</tr></table>';
        } else {
            // === SwitchBoard (single entry) ===
            $single = $parts[0]['circuit_description'] ?? '<em>(no description)</em>';
            $desc   = '<div>' . htmlspecialchars($single) . '</div>';
        }

        $circuits[] = [
            'circuit_number'      => $row['base_circuit_no'],
            'circuit_description' => $desc,
            'circuit_id'          => (int)$row['circuit_id']
        ];
    }
    $stmt->close();

    echo json_encode([
  'success'  => true,
  'circuits' => $circuits
]);

} catch (Exception $e) {
    error_log("Error fetching circuits: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'An error occurred while fetching circuits.']);
}
?>