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

// Admin check
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['serial_number'] ?? '');
    $property_id = intval($_POST['property_id'] ?? 0);
    $landlord_id = intval($_POST['landlord_id'] ?? 0);
    $description = trim($_POST['description'] ?? '');

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

header("Location: admin-dashboard.php");
exit();
