<?php
session_start();
require_once 'db_connect.php';

// Check admin access
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$stmt = $conn_rbe->prepare("SELECT role FROM rbe_roles WHERE user_id = ? LIMIT 1");
$stmt->execute([$user_id]);
if ($stmt->fetchColumn() !== 'admin') {
    exit('Access denied.');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $serial = trim($_POST['meter_serial'] ?? '');
    $phases = intval($_POST['phases'] ?? 0);
    $property_id = intval($_POST['property_id'] ?? 0);

    if ($serial && $phases && $property_id) {
        $stmt = $conn_rbe->prepare("INSERT INTO smart_meters (serial, phases, property_id) VALUES (?, ?, ?)");
        $stmt->execute([$serial, $phases, $property_id]);
        header("Location: admin-dashboard.php?msg=Meter+added+successfully");
        exit();
    } else {
        header("Location: admin-dashboard.php?msg=Error:+Please+fill+all+fields");
        exit();
    }
}
header("Location: admin-dashboard.php");
exit();
?>
