<?php
// /api/admin/reassign_meter.php
session_start();
require_once __DIR__ . '/../../core/db_connect.php';

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

$serial = $_POST['serial'] ?? '';
$source = strtoupper($_POST['source'] ?? '');
$property = $_POST['property_id'] ?? 0;
$tenant = $_POST['tenant_id'] ?? 0;

if (!$serial || !$source) {
    echo json_encode(['error' => 'Missing params']);
    exit;
}

try {
    if ($source === "IAMMETER") {
        $stmt = $conn_rbe->prepare("
            UPDATE smart_meters 
            SET property_id=?, tenant_id=?
            WHERE serial_number = ?
        ");
    }
    elseif ($source === "FLECTO") {
        $stmt = $conn_rbe->prepare("
            UPDATE flecto_meters 
            SET property_id=?, tenant_id=?
            WHERE serial_number = ?
        ");
    }
    else {
        $stmt = $conn_rbe->prepare("
            UPDATE water_meters 
            SET property_id=?, tenant_id=?
            WHERE serial_number = ?
        ");
    }

    $stmt->execute([$property, $tenant, $serial]);

    echo json_encode(['status' => 'ok']);

} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
