<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require_once 'db_connect.php';

// Check if user is logged in and is an admin
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = (int)$_SESSION['user_id'];

// Check role
$stmt = $conn_rbe->prepare("SELECT role FROM rbe_roles WHERE user_id = ? LIMIT 1");
$stmt->execute([$user_id]);
$role = $stmt->fetchColumn();

if ($role !== 'admin') {
    echo "Access denied. Admins only.";
    exit();
}

// CSRF token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf_token = $_SESSION['csrf_token'];

function esc($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }

// Handle Approve/Reject Actions for Agent Applications
$flash_ok = '';
$flash_err = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['agent_action'])) {
    $action = $_POST['agent_action']; // approve | reject
    $app_id = (int)($_POST['app_id'] ?? 0);
    $csrf   = $_POST['csrf_token'] ?? '';

    if (!hash_equals($_SESSION['csrf_token'], $csrf)) {
        $flash_err = 'Invalid session token. Please refresh.';
    } elseif (!$app_id) {
        $flash_err = 'Invalid application ID.';
    } else {
        try {
            $conn_rbe->beginTransaction();

            // NOTE: we must fetch fullname/email/phone because we use them later
            $s = $conn_rbe->prepare("
                SELECT id, user_id, fullname, email, phone, status
                FROM agent_applications
                WHERE id = ?
                LIMIT 1
            ");
            $s->execute([$app_id]);
            $app = $s->fetch(PDO::FETCH_ASSOC);

            if (!$app) {
                throw new RuntimeException('Application not found.');
            }
            if (!in_array($app['status'], ['pending','review'], true)) {
                throw new RuntimeException('Application already processed.');
            }

            if ($action === 'approve') {
                // 1) Mark application approved
                $u = $conn_rbe->prepare("UPDATE agent_applications SET status='approved', updated_at=NOW() WHERE id=?");
                $u->execute([$app_id]);

                // 2) Ensure user exists in rbe_users (standalone RBE user id)
                //    If already exists, refresh name/phone and un-delete.
                $up = $conn_rbe->prepare("
                    INSERT INTO rbe_users (id, fullname, email, phone, is_deleted)
                    VALUES (?, ?, ?, ?, 0)
                    ON DUPLICATE KEY UPDATE
                        fullname = VALUES(fullname),
                        phone    = VALUES(phone),
                        is_deleted = 0
                ");
                $up->execute([
                    (int)$app['user_id'],
                    (string)($app['fullname'] ?? ''),
                    (string)($app['email'] ?? ''),
                    (string)($app['phone'] ?? '')
                ]);

                // 3) Ensure agent role exists
                $chk = $conn_rbe->prepare("SELECT 1 FROM rbe_roles WHERE user_id = ? AND role='agent' LIMIT 1");
                $chk->execute([(int)$app['user_id']]);
                if (!$chk->fetchColumn()) {
                    $ins = $conn_rbe->prepare("INSERT INTO rbe_roles (user_id, role) VALUES (?, 'agent')");
                    $ins->execute([(int)$app['user_id']]);
                }

                $flash_ok = 'Agent application approved, user saved in rbe_users, and role assigned.';
            } elseif ($action === 'reject') {
                $u = $conn_rbe->prepare("UPDATE agent_applications SET status='rejected', updated_at=NOW() WHERE id=?");
                $u->execute([$app_id]);
                $flash_ok = 'Agent application rejected.';
            } else {
                throw new RuntimeException('Unknown action.');
            }

            $conn_rbe->commit();
        } catch (Throwable $e) {
            if ($conn_rbe->inTransaction()) $conn_rbe->rollBack();
            $flash_err = 'Error: ' . $e->getMessage();
        }
    }
}
// Handle Commission Update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_commission'])) {
    $agent_id = (int)($_POST['agent_id'] ?? 0);
    $rate     = (float)($_POST['commission_rate'] ?? 0);
    $csrf     = $_POST['csrf_token'] ?? '';

    if (!hash_equals($_SESSION['csrf_token'], $csrf)) {
        $flash_err = "Invalid session token. Please refresh.";
    } elseif ($agent_id <= 0) {
        $flash_err = "Invalid agent ID.";
    } else {
        try {
            $stmt = $conn_rbe->prepare("
                INSERT INTO commission_settings (agent_id, rate)
                VALUES (?, ?)
                ON DUPLICATE KEY UPDATE rate = VALUES(rate)
            ");
            $stmt->execute([$agent_id, $rate]);
            $flash_ok = "âœ… Commission rate updated for agent.";
        } catch (Throwable $e) {
            $flash_err = "Error: ".$e->getMessage();
        }
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>RBE Admin Dashboard</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
<style>
    body { font-family: Arial, sans-serif; background: #051a25; color: #ffffff; margin: 0; padding: 20px; }
    header { text-align: center; margin-bottom: 30px; }
    img.logo { width: 200px; margin-bottom: 10px; }
    h1 { color: #7ed957; font-size: 2.2em; margin-bottom: 20px; }
    .nav { display: flex; flex-wrap: wrap; justify-content: center; gap: 15px; margin: 0 auto 30px auto; max-width: 1000px; }
    .nav a { background: #7ed957; color: #000; padding: 15px 25px; border-radius: 12px; text-decoration: none; font-weight: bold; text-align: center; flex: 1 1 160px; box-shadow: 0 3px 8px rgba(0,0,0,0.4); transition: background 0.3s ease, transform 0.2s ease; }
    .nav a:hover { background: #00cc77; transform: translateY(-2px); }
    .section { background: #122c4c; padding: 25px; margin: 20px auto; border-radius: 15px; max-width: 1000px; box-shadow: 0 6px 20px rgba(0, 0, 0, 0.6); }
    .section h2, .section h3 { color: #7ed957; margin-top: 0; }
    table { width:100%; background:#1b3a4d; color:white; border-collapse:collapse; border-radius:8px; overflow:hidden; margin-top:15px; }
    table td, table th { text-align:center; border:none; font-size:0.95em; padding:12px; }
    table th { font-weight:bold; color:#7ed957; background:#0f2536; }
    table tr:hover { background-color:#1f4860; }
    .alert { margin: 10px 0; padding: 10px 14px; border-radius: 8px; }
    .ok { background:#0f3b2a; color:#b6ffcf; border:1px solid #176546; }
    .err { background:#3b0f0f; color:#ffd6d6; border:1px solid #6b1a1a; }
    input, select, button { padding:8px 12px; border-radius:6px; border:none; margin:4px; }
    button { cursor:pointer; background:#7ed957; color:#000; font-weight:bold; }
    button:hover { background:#00cc77; }
    body {
        font-family: Arial, sans-serif;
        background: #051a25;
        color: #ffffff;
        margin: 0;
        padding: 20px;
    }
    header {
        text-align: center;
        margin-bottom: 30px;
    }
    img.logo {
        width: 200px;
        margin-bottom: 10px;
    }
    h1 {
        color: #7ed957;
        font-size: 2.2em;
        margin-bottom: 20px;
    }
    .nav {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        gap: 15px;
        margin: 0 auto 30px auto;
        max-width: 1000px;
    }
    .nav a {
        background: #7ed957;
        color: #000;
        padding: 15px 25px;
        border-radius: 12px;
        text-decoration: none;
        font-weight: bold;
        text-align: center;
        flex: 1 1 160px;
        box-shadow: 0 3px 8px rgba(0,0,0,0.4);
        transition: background 0.3s ease, transform 0.2s ease;
    }
    .nav a:hover {
        background: #00cc77;
        transform: translateY(-2px);
    }
    .section {
        background: #122c4c;
        padding: 25px;
        margin: 20px auto;
        border-radius: 15px;
        max-width: 1000px;
        box-shadow: 0 6px 20px rgba(0, 0, 0, 0.6);
    }
    .section h2, .section h3 {
        color: #7ed957;
        margin-top: 0;
    }
    .quick-stats {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        gap: 20px;
        margin-top: 20px;
    }
    .stat-card {
        background: #1b3a4d;
        padding: 20px;
        border-radius: 12px;
        min-width: 140px;
        text-align: center;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
        flex: 1 1 150px;
        transition: transform 0.3s ease;
    }
    .stat-card:hover { transform: scale(1.05); }
    .stat-card h4 { margin: 5px 0; font-size: 1.1em; color: #7ed957; }
    .stat-card p { margin: 0; font-size: 1.4em; font-weight: bold; }
    @media (max-width: 480px) {
        .nav a { flex: 1 1 90%; }
        .section, .stat-card { width: 90%; }
    }
    table tr:hover { background-color: #1f4860; }
    table { width:100%; background:#1b3a4d; color:white; border-collapse:collapse; border-radius:8px; overflow:hidden; }
    table td, table th { text-align:center; border:none; font-size:0.95em; padding:12px; }
    table th { font-weight:bold; color:#7ed957; background:#0f2536; }
    a { color: #66b3ff; text-decoration: none; }
    a:hover { text-decoration: underline; color: #00ccff; }
    .stat-card1 {
        background: #7ed957; padding: 20px; border-radius: 12px; min-width: 140px;
        text-align: center; box-shadow: 0 4px 12px rgba(0,0,0,0.4); flex: 1 1 150px; transition: transform 0.3s ease;
    }
    .stat-card1:hover { transform: scale(1.05); }
    .stat-card1 h4 { margin: 5px 0; font-size: 1.1em; color: #1b3a4d; }
    .stat-card1 p { margin: 0; font-size: 1.4em; font-weight: bold; }
    .alert { margin: 10px 0; padding: 10px 14px; border-radius: 8px; }
    .ok { background:#0f3b2a; color:#b6ffcf; border:1px solid #176546; }
    .err { background:#3b0f0f; color:#ffd6d6; border:1px solid #6b1a1a; }
</style>
</head>
<body>
    <?php
$newAppUrl = RBE_V2_BASE_URL;
include __DIR__ . '/includes/new_app_banner.php';
?>

<header>
    <img src="https://rbelectrical.enterprises/wp-content/uploads/2024/07/RBE-Electrical-Logo-clear2-250x125.png" alt="RBE Logo" class="logo">
    <h1>RBE Admin Dashboard</h1>
</header>

<div class="nav">
    <a href="manage-agents.php">Manage Agents</a>
    <a href="manage-landlords.php">Manage Landlords</a>
    <a href="properties.php">Manage Properties</a>
    <a href="manage-tenants.php">Manage Tenants</a>
    <a href="admin-reports.php">Reports</a>
    <a href="logout.php">Logout</a>
</div>

<?php if ($flash_ok): ?><div class="section alert ok"><?= esc($flash_ok) ?></div><?php endif; ?>
<?php if ($flash_err): ?><div class="section alert err"><?= esc($flash_err) ?></div><?php endif; ?>


    <!-- Agent Applications Section -->
    <div class="section">
        <h2>Agent Applications (Pending/Review)</h2>
        <?php
        // Pagination & search
        $limit_apps = 10;
        $page_apps  = isset($_GET['page_apps']) ? max(1, (int)$_GET['page_apps']) : 1;
        $offset_apps = ($page_apps - 1) * $limit_apps;

        $search_email = trim($_GET['search_email'] ?? '');
        $where = "status IN ('pending','review')";
        $params = [];
        if ($search_email !== '') {
            $where .= " AND email LIKE :em";
            $params[':em'] = "%$search_email%";
        }

        // Totals
        $ts = $conn_rbe->prepare("SELECT COUNT(*) FROM agent_applications WHERE $where");
        $ts->execute($params);
        $total_apps = (int)$ts->fetchColumn();
        $total_pages_apps = max(1, (int)ceil($total_apps / $limit_apps));

        // Fetch rows
        $q = $conn_rbe->prepare("
            SELECT id, user_id, fullname, email, phone, company, website, notes, status, created_at
            FROM agent_applications
            WHERE $where
            ORDER BY created_at DESC
            LIMIT $limit_apps OFFSET $offset_apps
        ");
        $q->execute($params);
        ?>
        <form method="get" style="margin-bottom: 16px; text-align:center;">
            <input type="text" name="search_email" placeholder="Filter by emailâ€¦" value="<?= esc($search_email) ?>" style="padding:8px;border-radius:6px;width:220px;">
            <button type="submit" style="padding:8px 12px;background:#7ed957;color:black;border:none;border-radius:6px;cursor:pointer;">Search</button>
        </form>

        <table>
            <tr>
                <th>Applicant</th>
                <th>Contact</th>
                <th>Company</th>
                <th>Website</th>
                <th>Applied</th>
                <th>Actions</th>
            </tr>
            <?php while ($app = $q->fetch(PDO::FETCH_ASSOC)): ?>
                <tr>
                    <td>
                        <div><strong><?= esc($app['fullname']) ?></strong></div>
                        <div class="mut" style="font-size:.9em;color:#bfe8ff;max-width:240px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
                            <?= esc($app['notes'] ?: 'â€”') ?>
                        </div>
                    </td>
                    <td>
                        <div><?= esc($app['email']) ?></div>
                        <div><?= esc($app['phone']) ?></div>
                    </td>
                    <td><?= esc($app['company'] ?: 'â€”') ?></td>
                    <td>
                        <?php if (!empty($app['website'])): ?>
                            <a href="<?= esc($app['website']) ?>" target="_blank" rel="noopener">Visit</a>
                        <?php else: ?>
                            â€”
                        <?php endif; ?>
                    </td>
                    <td><?= esc($app['created_at']) ?></td>
                    <td>
                        <form method="post" style="display:inline;">
                            <input type="hidden" name="csrf_token" value="<?= esc($csrf_token) ?>">
                            <input type="hidden" name="app_id" value="<?= (int)$app['id'] ?>">
                            <button type="submit" name="agent_action" value="approve" style="padding:6px 10px;border:none;border-radius:6px;background:#7ed957;color:#000;cursor:pointer;">Approve</button>
                        </form>
                        <form method="post" style="display:inline;margin-left:6px;">
                            <input type="hidden" name="csrf_token" value="<?= esc($csrf_token) ?>">
                            <input type="hidden" name="app_id" value="<?= (int)$app['id'] ?>">
                            <button type="submit" name="agent_action" value="reject" style="padding:6px 10px;border:none;border-radius:6px;background:#b54646;color:#fff;cursor:pointer;">Reject</button>
                        </form>
                    </td>
                </tr>
            <?php endwhile; ?>
        </table>

        <div style="text-align:center;margin-top:16px;">
            <?php if ($page_apps > 1): ?>
                <a href="?page_apps=<?= $page_apps - 1 ?>&search_email=<?= urlencode($search_email) ?>" style="color:#7ed957;margin:0 10px;">Â« Prev</a>
            <?php endif; ?>
            <span>Page <?= $page_apps ?> of <?= $total_pages_apps ?></span>
            <?php if ($page_apps < $total_pages_apps): ?>
                <a href="?page_apps=<?= $page_apps + 1 ?>&search_email=<?= urlencode($search_email) ?>" style="color:#7ed957;margin:0 10px;">Next Â»</a>
            <?php endif; ?>
        </div>
    </div>

    <div class="section">
    <h2>Quick Stats</h2>
    <div class="quick-stats">
        <?php
        $landlords = $conn_rbe->query("SELECT COUNT(*) FROM rbe_roles WHERE role = 'landlord'")->fetchColumn();
        $tenants = $conn_rbe->query("SELECT COUNT(*) FROM rbe_roles WHERE role = 'tenant'")->fetchColumn();
        $properties = $conn_rbe->query("SELECT COUNT(*) FROM properties")->fetchColumn();

        $flecto_meters = $conn_rbe->query("SELECT COUNT(*) FROM flecto_meters")->fetchColumn();
        $iammeters = $conn_rbe->query("SELECT COUNT(*) FROM smart_meters")->fetchColumn(); // IAMMETER assumed
        $water_meters = $conn_rbe->query("SELECT COUNT(*) FROM water_meters")->fetchColumn();
        $agents = $conn_rbe->query("SELECT COUNT(*) FROM rbe_roles WHERE role = 'agent'")->fetchColumn();

        $total_meters = $flecto_meters + $iammeters + $water_meters;
        
        echo "<div class='stat-card'><h4>Agents</h4><p>$agents</p></div>";
        echo "<div class='stat-card'><h4>Landlords</h4><p>$landlords</p></div>";
        echo "<div class='stat-card'><h4>Tenants</h4><p>$tenants</p></div>";
        echo "<div class='stat-card'><h4>Properties</h4><p>$properties</p></div>";

        echo "<div class='stat-card'><h4>IAMMETER Meters</h4><p>$iammeters</p></div>";
        echo "<div class='stat-card'><h4>FLECTO Meters</h4><p>$flecto_meters</p></div>";
        echo "<div class='stat-card'><h4>Water Meters</h4><p>$water_meters</p></div>";
        echo "<div class='stat-card1'><h4>Total Meters</h4><p>$total_meters</p></div>";
        ?>
    </div>
    </div>

    <div class="section">
        <h2 style="color:#7ed957;">Meter Management</h2>

    <!-- IAMMETER Meter Form -->
    <h3>Add IAMMETER Meter</h3>
    <form method="post" action="">
        <input type="text" name="meter_serial" placeholder="Meter Serial" required>
        <input type="number" name="phases" placeholder="Phases (1 or 3)" required>

        <select name="property_id" required>
            <option value="">Assign to Property</option>
            <?php
            $stmt = $conn_rbe->query("SELECT id, property_number FROM properties ORDER BY property_number ASC");
            while ($prop = $stmt->fetch()) {
                echo "<option value='{$prop['id']}'>{$prop['property_number']}</option>";
            }
            ?>
        </select>

        <select name="landlord_id" required>
            <option value="">Assign to Landlord</option>
            <?php
            $stmt = $conn_rbe->query("
                SELECT u.id, u.fullname 
                FROM rbe_users u 
                JOIN rbe_roles r ON u.id = r.user_id 
                WHERE r.role = 'landlord' 
                ORDER BY u.fullname ASC
            ");
            while ($ll = $stmt->fetch()) {
                echo "<option value='{$ll['id']}'>{$ll['fullname']}</option>";
            }
            ?>
        </select>

        <select name="tenant_id" required>
            <option value="">Assign to Tenant</option>
            <?php
            $stmt = $conn_rbe->query("
                SELECT u.id, u.fullname 
                FROM rbe_users u 
                JOIN rbe_roles r ON u.id = r.user_id 
                WHERE r.role = 'tenant' 
                ORDER BY u.fullname ASC
            ");
            while ($t = $stmt->fetch()) {
                echo "<option value='{$t['id']}'>{$t['fullname']}</option>";
            }
            ?>
        </select>

        <button type="submit" name="add_meter">Add IAMMETER Meter</button>
    </form>

    <!-- IAMMETER Insert Logic -->
    <?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_meter'])) {
        $serial = trim($_POST['meter_serial']);
        $phases = intval($_POST['phases']);
        $property_id = intval($_POST['property_id']);
        $landlord_id = intval($_POST['landlord_id']);
        $tenant_id = intval($_POST['tenant_id']);

        if ($serial && $phases && $property_id && $landlord_id && $tenant_id) {
            $stmt = $conn_rbe->prepare("
                INSERT INTO smart_meters (serial, phases, property_id, landlord_id, tenant_id, source_type, meter_type) 
                VALUES (?, ?, ?, ?, ?, 'IAMMETER', 'electricity')
            ");
            $stmt->execute([$serial, $phases, $property_id, $landlord_id, $tenant_id]);
            echo "<p style='color:#7ed957;'>âœ… IAMMETER meter added!</p>";
        } else {
            echo "<p style='color:#ff6666;'>âŒ Please fill all fields.</p>";
        }
    }
    ?>

    <hr style="margin: 40px 0; border-color: #2e4e65;">

    <!-- WATER Meter Form -->
    <h3>Add WATER Meter</h3>
    <form method="POST" action="add_water_meter.php">
        <input name="serial_number" placeholder="Flecto Serial Number" required>
        <input name="description" placeholder="Description (e.g. Kitchen Tap)">
        
        <select name="property_id" required>
            <option value="">Assign to Property</option>
            <?php
            $stmt = $conn_rbe->query("SELECT id, property_number FROM properties");
            while ($prop = $stmt->fetch()) {
                echo "<option value='{$prop['id']}'>{$prop['property_number']}</option>";
            }
            ?>
        </select>

        <select name="landlord_id" required>
            <option value="">Assign to Landlord</option>
            <?php
            $stmt = $conn_rbe->query("
                SELECT u.id, u.fullname 
                FROM rbe_users u 
                JOIN rbe_roles r ON u.id = r.user_id 
                WHERE r.role = 'landlord'
            ");
            while ($ll = $stmt->fetch()) {
                echo "<option value='{$ll['id']}'>{$ll['fullname']}</option>";
            }
            ?>
        </select>

        <!-- FIXED: this select had the wrong name previously -->
        <select name="tenant_id" required>
            <option value="">Assign to Tenant</option>
            <?php
            $stmt = $conn_rbe->query("
                SELECT u.id, u.fullname 
                FROM rbe_users u 
                JOIN rbe_roles r ON u.id = r.user_id 
                WHERE r.role = 'tenant'
            ");
            while ($ll = $stmt->fetch()) {
                echo "<option value='{$ll['id']}'>{$ll['fullname']}</option>";
            }
            ?>
        </select>

        <button type="submit">Add WATER Meter</button>
    </form>
    <hr style="margin: 40px 0; border-color: #2e4e65;">
    
    <!-- FLECTO Meter adding Form -->
    <h3>Add FLECTO Meter</h3>
    <form method="post" action="">
        <input type="text" name="serial_number" placeholder="Flecto Serial Number" required>
        <input type="text" name="description" placeholder="Description (e.g. Sub DB)" required>

        <select name="property_id" required>
            <option value="">Assign to Property</option>
            <?php
            $stmt = $conn_rbe->query("SELECT id, property_number FROM properties");
            while ($prop = $stmt->fetch()) {
                echo "<option value='{$prop['id']}'>{$prop['property_number']}</option>";
            }
            ?>
        </select>

        <select name="landlord_id" required>
            <option value="">Assign to Landlord</option>
            <?php
            $stmt = $conn_rbe->query("
                SELECT u.id, u.fullname 
                FROM rbe_users u 
                JOIN rbe_roles r ON u.id = r.user_id 
                WHERE r.role = 'landlord'
            ");
            while ($ll = $stmt->fetch()) {
                echo "<option value='{$ll['id']}'>{$ll['fullname']}</option>";
            }
            ?>
        </select>
        
        <select name="tenant_id" required>
            <option value="">Assign to Tenant</option>
            <?php
            $stmt = $conn_rbe->query("
                SELECT u.id, u.fullname 
                FROM rbe_users u 
                JOIN rbe_roles r ON u.id = r.user_id 
                WHERE r.role = 'tenant'
            ");
            while ($t = $stmt->fetch()) {
                echo "<option value='{$t['id']}'>{$t['fullname']}</option>";
            }
            ?>
        </select>

        <button type="submit" name="add_flecto_meter">Add FLECTO Meter</button>
    </form>

    <!-- FLECTO Insert Logic -->
    <?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_flecto_meter'])) {
        $serial = trim($_POST['serial_number']);
        $description = trim($_POST['description']);
        $property_id = intval($_POST['property_id']);
        $landlord_id = intval($_POST['landlord_id']);
        $tenant_id = intval($_POST['tenant_id']);

        if ($serial && $description && $property_id && $landlord_id && $tenant_id) {
            $stmt = $conn_rbe->prepare("
                INSERT INTO flecto_meters (serial_number, description, property_id, landlord_id, tenant_id, is_active)
                VALUES (?, ?, ?, ?, ?, 1)
            ");
            $stmt->execute([$serial, $description, $property_id, $landlord_id, $tenant_id]);
            echo "<p style='color:#7ed957;'>âœ… FLECTO meter added!</p>";
        } else {
            echo "<p style='color:#ff6666;'>âŒ Please fill all fields.</p>";
        }
    }
    ?>
    <!-- END of FLECTO meter -->
    </div>

    <div>
        <section>
            <h1>Existing Meters</h1>
        </section>
        
        <section style="margin-top: 40px;">
            <h3 style="color:#7ed957; margin-bottom: 20px;">âš¡ IAMMETER Meters</h3>

            <?php
            // IAMMETER pagination setup
            $limit = 5;
            $page_iam = isset($_GET['page_iam']) ? max(1, intval($_GET['page_iam'])) : 1;
            $offset = ($page_iam - 1) * $limit;

            // Get total IAMMETER count
            $total_stmt = $conn_rbe->query("
                SELECT COUNT(*) FROM smart_meters 
                WHERE source_type = 'IAMMETER' AND meter_type = 'electricity'
            ");
            $total = $total_stmt->fetchColumn();
            $total_pages = ceil($total / $limit);

            // Paginated query
            $stmt = $conn_rbe->prepare("
                SELECT m.id, m.serial, m.phases, p.property_number 
                FROM smart_meters m 
                LEFT JOIN properties p ON m.property_id = p.id 
                WHERE m.source_type = 'IAMMETER' AND m.meter_type = 'electricity'
                ORDER BY m.serial ASC
                LIMIT $limit OFFSET $offset
            ");
            $stmt->execute();
            ?>

            <table>
                <tr>
                    <th>Serial</th>
                    <th>Phases</th>
                    <th>Property</th>
                    <th>Actions</th>
                </tr>
                <?php while ($row = $stmt->fetch()): ?>
                    <tr>
                        <td><?= esc($row['serial']) ?></td>
                        <td><?= intval($row['phases']) ?></td>
                        <td><?= esc($row['property_number'] ?? 'Unassigned') ?></td>
                        <td>
                            <a href="reassign_meter.php?id=<?= (int)$row['id'] ?>">Reassign</a> |
                            <a href="delete_meter.php?id=<?= (int)$row['id'] ?>" style="color:#ff6666;">Delete</a>
                        </td>
                    </tr>
                <?php endwhile; ?>
            </table>

            <!-- Pagination for IAMMETER -->
            <div style="text-align: center; margin-top: 20px;">
                <?php if ($page_iam > 1): ?>
                    <a href="?page_iam=<?= $page_iam - 1 ?>" style="color:#7ed957; margin: 0 10px;">&laquo; Prev</a>
                <?php endif; ?>

                <span style="margin: 0 10px;">Page <?= $page_iam ?> of <?= $total_pages ?></span>

                <?php if ($page_iam < $total_pages): ?>
                    <a href="?page_iam=<?= $page_iam + 1 ?>" style="color:#7ed957; margin: 0 10px;">Next &raquo;</a>
                <?php endif; ?>
            </div>
        </section>

        <hr style="margin: 40px 0; border-color: #2e4e65;">

        <section style="margin-top: 40px;">
            <h3 style="color:#7ed957; margin-bottom: 20px;">âš¡ FLECTO Meters</h3>

            <?php
            // Pagination setup
            $limit = 5;
            $page_flecto = isset($_GET['page_flecto']) ? max(1, intval($_GET['page_flecto'])) : 1;
            $offset = ($page_flecto - 1) * $limit;

            // Get total FLECTO meters
            $total_stmt = $conn_rbe->query("SELECT COUNT(*) FROM flecto_meters WHERE is_active = 1");
            $total_flecto = $total_stmt->fetchColumn();
            $total_pages = ceil($total_flecto / $limit);

            // Paginated query
            $stmt = $conn_rbe->prepare("
                SELECT f.id, f.serial_number, f.description, p.property_number
                FROM flecto_meters f
                LEFT JOIN properties p ON f.property_id = p.id
                WHERE f.is_active = 1
                ORDER BY f.serial_number ASC
                LIMIT $limit OFFSET $offset
            ");
            $stmt->execute();
            ?>

            <table>
                <tr>
                    <th>Serial</th>
                    <th>Description</th>
                    <th>Property</th>
                    <th>Actions</th>
                </tr>
                <?php while ($row = $stmt->fetch()): ?>
                    <tr>
                        <td><?= esc($row['serial_number']) ?></td>
                        <td><?= esc($row['description'] ?? 'â€”') ?></td>
                        <td><?= esc($row['property_number'] ?? 'Unassigned') ?></td>
                        <td>
                            <a href="reassign_flecto_meter.php?id=<?= (int)$row['id'] ?>">Reassign</a> |
                            <a href="delete_flecto_meter.php?id=<?= (int)$row['id'] ?>" style="color:#ff6666;">Delete</a>
                        </td>
                    </tr>
                <?php endwhile; ?>
            </table>

            <!-- Pagination for FLECTO -->
            <div style="text-align: center; margin-top: 20px;">
                <?php if ($page_flecto > 1): ?>
                    <a href="?page_flecto=<?= $page_flecto - 1 ?>" style="color:#7ed957; margin: 0 10px;">&laquo; Prev</a>
                <?php endif; ?>

                <span style="margin: 0 10px;">Page <?= $page_flecto ?> of <?= $total_pages ?></span>

                <?php if ($page_flecto < $total_pages): ?>
                    <a href="?page_flecto=<?= $page_flecto + 1 ?>" style="color:#7ed957; margin: 0 10px;">Next &raquo;</a>
                <?php endif; ?>
            </div>
        </section>

        <div class="section" style="margin-top: 40px;">
            <h3 style="color:#7ed957; margin-bottom: 20px;">ðŸ’§ WATER Meters</h3>

            <?php
            // Set pagination variables
            $limit = 5;
            $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
            $offset = ($page - 1) * $limit;

            // Get search term (if any)
            $search_serial = trim($_GET['search_serial'] ?? '');

            // Prepare WHERE condition
            $where_clause = "w.is_active = 1";
            $params = [];

            if ($search_serial !== '') {
                $where_clause .= " AND w.serial_number LIKE ?";
                $params[] = "%$search_serial%";
            }

            // Get total count (with optional search)
            $total_stmt = $conn_rbe->prepare("SELECT COUNT(*) FROM water_meters w WHERE $where_clause");
            $total_stmt->execute($params);
            $total_meters = $total_stmt->fetchColumn();
            $total_pages = ceil($total_meters / $limit);

            // Get paginated results
            $sql = "
                SELECT 
                    w.id, 
                    w.serial_number, 
                    w.description, 
                    w.landlord_id,
                    u.fullname AS landlord_name,
                    p.property_number
                FROM water_meters w
                LEFT JOIN properties p ON w.property_id = p.id
                LEFT JOIN rbe_users u ON w.landlord_id = u.id
                WHERE $where_clause
                ORDER BY w.serial_number ASC
                LIMIT $limit OFFSET $offset";
            $stmt = $conn_rbe->prepare($sql);
            $stmt->execute($params);
            ?>
            <form method="get" style="margin-bottom: 20px; text-align: center;">
                <input type="text" name="search_serial" placeholder="Serial Number..." 
                    value="<?= esc($_GET['search_serial'] ?? '') ?>"
                    style="padding: 8px; border-radius: 6px; width: 180px;">

                <button type="submit" style="padding: 8px 12px; background:#7ed957; color:black; border:none; border-radius: 6px; cursor:pointer;">
                    Search
                </button>
            </form>

            <table>
                <tr>
                    <th>Serial</th>
                    <th>Landlord</th>
                    <th>Property</th>
                    <th>Actions</th>
                </tr>
                <?php while ($row = $stmt->fetch()): ?>
                    <tr>
                        <td><?= esc($row['serial_number']) ?></td>
                        <td><?= esc($row['landlord_name'] ?? 'Unassigned') ?></td>
                        <td><?= esc($row['property_number'] ?? 'Unassigned') ?></td>
                        <td>
                            <a href="reassign_water_meter.php?id=<?= (int)$row['id'] ?>">Reassign</a> |
                            <a href="delete_water_meter.php?id=<?= (int)$row['id'] ?>" style="color:#ff6666;">Delete</a>
                        </td>
                    </tr>
                <?php endwhile; ?>
            </table>

            <!-- Pagination Links -->
            <?php if ($page > 1): ?>
            <a href="?page=<?= $page - 1 ?>&search_serial=<?= urlencode($search_serial) ?>" style="color:#7ed957; margin: 0 10px;">&laquo; Prev</a>
            <?php endif; ?>

            <span style="margin: 0 10px;">Page <?= $page ?> of <?= $total_pages ?></span>

            <?php if ($page < $total_pages): ?>
                <a href="?page=<?= $page + 1 ?>&search_serial=<?= urlencode($search_serial) ?>" style="color:#7ed957; margin: 0 10px;">Next &raquo;</a>
            <?php endif; ?>
        </div>
    <!-- Commission Management Section -->
<div class="section">
    <h2>ðŸ’° Commission Management</h2>
    <p>Set and update commission rates for each agent (ZAR per meter):</p>
    <table>
        <tr>
            <th>Agent</th>
            <th>Email</th>
            <th>Current Rate / meter</th>
            <th>Update</th>
        </tr>
        <?php
        $agents = $conn_rbe->query("
            SELECT u.id, u.fullname, u.email, cs.rate
            FROM rbe_users u
            JOIN rbe_roles r ON r.user_id=u.id AND r.role='agent'
            LEFT JOIN commission_settings cs ON cs.agent_id=u.id
            ORDER BY u.fullname ASC
        ");
        while ($ag = $agents->fetch(PDO::FETCH_ASSOC)): ?>
            <tr>
                <td><?= esc($ag['fullname']) ?></td>
                <td><?= esc($ag['email']) ?></td>
                <td><?= esc($ag['rate'] ?? 0) ?> ZAR</td>
                <td>
                    <form method="post" style="display:inline-flex; align-items:center; gap:6px;">
                        <input type="hidden" name="csrf_token" value="<?= esc($csrf_token) ?>">
                        <input type="hidden" name="agent_id" value="<?= (int)$ag['id'] ?>">
                        <input type="number" name="commission_rate" step="1" min="0" value="<?= esc($ag['rate'] ?? 0) ?>" style="width:80px;">
                        <button type="submit" name="update_commission">Save</button>
                    </form>
                </td>
            </tr>
        <?php endwhile; ?>
    </table>
</div>


</body>
</html>
    </div>
    
</body>
</html>




