<?php
// elec_update_circuit.php

header('Content-Type: application/json');

// 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 {
    exit(json_encode(['success'=>false,'message'=>'Configuration file not found.']));
}

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

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

$circuit_id = intval($_POST['circuit_id']);
$parts_json = $_POST['parts'];

// Optional: sanity-check JSON
if (json_decode($parts_json) === null) {
    exit(json_encode(['success'=>false,'message'=>'Invalid JSON for parts.']));
}

// 4) Update
$stmt = $con->prepare("UPDATE elec_circuit SET parts = ? WHERE circuit_id = ?");
if (!$stmt) {
    exit(json_encode(['success'=>false,'message'=>'DB prepare error: '.$con->error]));
}
$stmt->bind_param("si",$parts_json,$circuit_id);
if (!$stmt->execute()) {
    exit(json_encode(['success'=>false,'message'=>'Update failed: '.$stmt->error]));
}

echo json_encode(['success'=>true,'message'=>'Circuit updated.']);