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

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

$serial = $_POST['serial'] ?? '';
$source = strtoupper($_POST['source'] ?? '');

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

try {
    // Archive
    $conn_rbe->prepare("
        INSERT INTO archived_meters (serial_number, source, archived_at)
        VALUES (?, ?, NOW())
    ")->execute([$serial, $source]);

    // Remove from active table
    if ($source === "IAMMETER") {
        $conn_rbe->prepare("DELETE FROM smart_meters WHERE serial_number=?")
                ->execute([$serial]);
    }
    elseif ($source === "FLECTO") {
        $conn_rbe->prepare("DELETE FROM flecto_meters WHERE serial_number=?")
                ->execute([$serial]);
    }
    else {
        $conn_rbe->prepare("DELETE FROM water_meters WHERE serial_number=?")
                ->execute([$serial]);
    }

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

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