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

$user_id = $_SESSION['user_id'] ?? 0;

// Role check
$role = $conn_rbe->prepare("SELECT role FROM rbe_roles WHERE user_id=?");
$role->execute([$user_id]);
if ($role->fetchColumn() !== 'agent') die("Access denied");

// Meter type from query
$type = $_GET['type'] ?? '';
if (!in_array($type, ['smart','flecto','water'])) die("Invalid meter type");

// Agent details
$agent = $conn_rbe->prepare("
  SELECT u.fullname, u.email, r.company
  FROM rbe_users u
  LEFT JOIN rbe_agents r ON r.user_id=u.id
  WHERE u.id=?
");
$agent->execute([$user_id]);
$agent = $agent->fetch(PDO::FETCH_ASSOC) ?: [];

// Fetch agent’s properties
$properties = $conn_rbe->prepare("
    SELECT id, property_number, landlord_id 
    FROM properties 
    WHERE agent_id=? 
    ORDER BY created_at DESC
");
$properties->execute([$user_id]);
$properties = $properties->fetchAll(PDO::FETCH_ASSOC);

$flash_err = '';

// Handle form
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $property_id = (int)($_POST['property_id'] ?? 0);

    // Fetch landlord linked to this property
    $stmt = $conn_rbe->prepare("SELECT landlord_id FROM properties WHERE id=? AND agent_id=?");
    $stmt->execute([$property_id, $user_id]);
    $landlord_id = $stmt->fetchColumn();

    if ($type === 'smart') {
        $serial = trim($_POST['serial'] ?? '');
        $phases = (int)($_POST['phases'] ?? 0);
        if ($serial && $phases && $property_id && $landlord_id) {
            $stmt = $conn_rbe->prepare("
                INSERT INTO smart_meters (serial, phases, property_id, landlord_id, agent_id, source_type, meter_type)
                VALUES (?, ?, ?, ?, ?, 'IAMMETER', 'electricity')
            ");
            $stmt->execute([$serial, $phases, $property_id, $landlord_id, $user_id]);
            header("Location: /agents/manage.php?meter=smart");
            exit;
        } else {
            $flash_err = "All fields are required.";
        }

    } elseif ($type === 'flecto') {
        $serial = trim($_POST['serial_number'] ?? '');
        $desc   = trim($_POST['description'] ?? '');
        if ($serial && $desc && $property_id && $landlord_id) {
            $stmt = $conn_rbe->prepare("
                INSERT INTO flecto_meters (serial_number, description, property_id, landlord_id, agent_id, is_active)
                VALUES (?, ?, ?, ?, ?, 1)
            ");
            $stmt->execute([$serial, $desc, $property_id, $landlord_id, $user_id]);
            header("Location: /agents/manage.php?meter=flecto");
            exit;
        } else {
            $flash_err = "All fields are required.";
        }

    } elseif ($type === 'water') {
        $serial = trim($_POST['serial_number'] ?? '');
        $desc   = trim($_POST['description'] ?? '');
        if ($serial && $property_id && $landlord_id) {
            $stmt = $conn_rbe->prepare("
                INSERT INTO water_meters (serial_number, description, property_id, landlord_id, agent_id, is_active)
                VALUES (?, ?, ?, ?, ?, 1)
            ");
            $stmt->execute([$serial, $desc, $property_id, $landlord_id, $user_id]);
            header("Location: /agents/manage.php?meter=water");
            exit;
        } else {
            $flash_err = "All fields are required.";
        }
    }
}
?>
<link rel="stylesheet" href="/agents/includes/styles.css">

<header>
  <img src="https://rbelectrical.enterprises/wp-content/uploads/2024/07/RBE-Electrical-Logo-clear2-250x125.png" class="logo" alt="Logo">
  <div class="title-group">
    <h1>Add <?=strtoupper($type)?> Meter</h1>
    <h2><?=htmlspecialchars($agent['fullname'] ?? 'Unknown Agent')?></h2>
    <?php if (!empty($agent['company'])): ?>
      <p><?=htmlspecialchars($agent['company'])?></p>
    <?php endif; ?>
    <p><?=htmlspecialchars($agent['email'] ?? '')?></p>
  </div>
</header>

<nav class="nav">
  <a href="/agents/dashboard.php">Dashboard</a>
  <a href="/agents/manage.php">My Clients</a>
  <a href="/agents/commissions.php">Commissions</a>
  <a href="/agents/profile.php">Profile</a>
</nav>

<section class="section">
  <?php if ($flash_err): ?><p class="error"><?=$flash_err?></p><?php endif; ?>

  <form method="post" class="form">
    <?php if ($type === 'smart'): ?>
      <label>Serial:
        <input type="text" name="serial" required>
      </label>
      <label>Phases:
        <input type="number" name="phases" min="1" max="3" required>
      </label>
    <?php elseif ($type === 'flecto' || $type === 'water'): ?>
      <label>Serial Number:
        <input type="text" name="serial_number" required>
      </label>
      <label>Description:
        <input type="text" name="description">
      </label>
    <?php endif; ?>

    <label>Assign to Property:
      <select name="property_id" required>
        <option value="">-- Select Property --</option>
        <?php foreach($properties as $p): ?>
          <option value="<?=$p['id']?>"><?=htmlspecialchars($p['property_number'])?></option>
        <?php endforeach; ?>
      </select>
    </label>

    <button type="submit" class="btn">Save Meter</button>
    <a href="/agents/manage.php" class="btn">Back</a>
  </form>
</section>

<style>
.form label {display:block;margin:10px 0;}
.form input, .form select {
  width:100%;padding:8px;border:1px solid #ccc;border-radius:4px;
}
.error {color:red;font-weight:600;}
</style>
