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

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

// Sanitize input
$circuit_id = intval($_POST['circuit_id']);

// Check if the circuit exists
$query = "SELECT circuit_id FROM elec_circuit WHERE circuit_id = ?";
$stmt = $con->prepare($query);
$stmt->bind_param('i', $circuit_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'Circuit not found.']);
    exit;
}
$stmt->close();

// Delete the circuit
$query = "DELETE FROM elec_circuit WHERE circuit_id = ?";
$stmt = $con->prepare($query);
$stmt->bind_param('i', $circuit_id);

if ($stmt->execute()) {
    echo json_encode(['success' => true, 'message' => 'Circuit deleted successfully.']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to delete circuit.']);
}

$stmt->close();
$con->close();