<?php
// elec_add_circuit.php

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

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

// Required fields
foreach (['tenant','board_id','clientnumber','locnumber','base_circuit_no','parts','circuit_mode'] as $f) {
    if (!isset($_POST[$f]) || $_POST[$f] === '') {
        die(json_encode([
            'success' => false,
            'message' => "Missing required field: $f"
        ]));
    }
}

// Decode parts JSON
$parts = json_decode($_POST['parts'], true);
if (!is_array($parts) || count($parts) < 1) {
    die(json_encode([
        'success' => false,
        'message' => 'Invalid parts JSON.'
    ]));
}

// Verify count matches mode
$mode = $_POST['circuit_mode'];
if ($mode === 'LV' && count($parts) !== 3) {
    die(json_encode([
        'success' => false,
        'message' => 'LV mode requires 3 spurs.'
    ]));
}
if ($mode === 'SwitchBoard' && count($parts) !== 1) {
    die(json_encode([
        'success' => false,
        'message' => 'SwitchBoard mode requires a single entry.'
    ]));
}

// Prepare insert
$sql = "
    INSERT INTO elec_circuit
      (board_id, clientnumber, locnumber, base_circuit_no, parts)
    VALUES (?, ?, ?, ?, ?)";
$stmt = $con->prepare($sql);
if (!$stmt) {
    die(json_encode([
        'success' => false,
        'message' => 'DB prepare error: ' . $con->error
    ]));
}

$board   = intval($_POST['board_id']);
$client  = intval($_POST['clientnumber']);
$loc     = intval($_POST['locnumber']);
$base    = $_POST['base_circuit_no'];
$partsJson = json_encode($parts, JSON_UNESCAPED_SLASHES);

// Bind & execute
$stmt->bind_param("iiiss", $board, $client, $loc, $base, $partsJson);
if (!$stmt->execute()) {
    die(json_encode([
        'success' => false,
        'message' => 'Insert failed: ' . $stmt->error
    ]));
}
$stmt->close();

// Success
echo json_encode([
    'success' => true,
    'message' => 'Circuit added successfully.'
]);