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

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");

// Agent details
$agent = $conn_rbe->prepare("
  SELECT u.fullname, u.email, r.company, r.commission_rate, r.phone
  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) ?: [];

// Flash
$flash_ok = '';
$flash_err = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $property_number = trim($_POST['property_number'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $square_meters = $_POST['square_meters'] !== '' ? (float)$_POST['square_meters'] : null;

    if ($property_number) {
        try {
            $stmt = $conn_rbe->prepare("
                INSERT INTO properties (landlord_id, agent_id, property_number, address, square_meters)
                VALUES (NULL, ?, ?, ?, ?)
            ");
            $ok = $stmt->execute([$user_id, $property_number, $address, $square_meters]);

            if ($ok) {
                header("Location: /agents/manage.php?added=1");
                exit;
            } else {
                $flash_err = "Failed to add property.";
            }
        } catch (PDOException $e) {
            $flash_err = "Database error: " . $e->getMessage();
        }
    } else {
        $flash_err = "Property number is 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 Property</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">
    <label>Property Number:
      <input type="text" name="property_number" required>
    </label>
    <label>Address:
      <input type="text" name="address">
    </label>
    <label>Square Meters:
      <input type="number" step="0.01" name="square_meters">
    </label>
    <button type="submit" class="btn">Save Property</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>
