<?php
// Enable error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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.']));
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
    exit;
}

// Validate required parameters
if (!isset($_POST['board_id']) || !isset($_POST['circuit_id'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required parameters.']);
    exit;
}

$board_id = intval($_POST['board_id']);
$circuit_id = intval($_POST['circuit_id']);

// Fetch all spurs for the given circuit
$query = "
    SELECT 
        circuit_no,
        circuit_description,
        cable_type,
        reference_method,
        number_size_live,
        number_size_cpc,
        bsen,
        bs_type,
        rating,
        breaking_capacity,
        rcd_tripping_current,
        rcd_type,
        max_allowed_zs
    FROM elec_circuit
    WHERE board_id = ? AND SUBSTRING_INDEX(circuit_no, 'L', 1) = (
        SELECT SUBSTRING_INDEX(circuit_no, 'L', 1)
        FROM elec_circuit
        WHERE circuit_id = ?
    )
    ORDER BY circuit_no
";

$stmt = $con->prepare($query);
if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'Database query preparation failed: ' . $con->error]);
    exit;
}

$stmt->bind_param("ii", $board_id, $circuit_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    $circuits = [];
    while ($row = $result->fetch_assoc()) {
        $circuits[] = $row;
    }
    echo json_encode(['success' => true, 'data' => $circuits]);
} else {
    echo json_encode(['success' => false, 'message' => 'No spurs found for the specified circuit.']);
}

$stmt->close();
?>