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

require_once __DIR__ . '/../db_connect.php';
require_once __DIR__ . '/../vendor/autoload.php'; // ✅ load PHPMailer once

// Namespace imports must be at the top level
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

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, u.company, u.phone
  FROM rbe_users u
  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 
    FROM properties 
    WHERE agent_id=? 
    ORDER BY created_at DESC
");
$properties->execute([$user_id]);
$properties = $properties->fetchAll(PDO::FETCH_ASSOC);

$flash_err = '';
$flash_ok  = '';

// Handle Add Landlord
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_landlord'])) {
    $fullname    = trim($_POST['fullname'] ?? '');
    $email       = trim($_POST['email'] ?? '');
    $phone       = trim($_POST['phone'] ?? '');
    $property_id = (int)($_POST['property_id'] ?? 0);

    if ($fullname && $email && $property_id) {
        try {
            $conn_rbe->beginTransaction();

            // Step 1: Find or create standalone RBE user
            $stmt = $conn_rbe->prepare("SELECT id FROM rbe_users WHERE email=? LIMIT 1");
            $stmt->execute([$email]);
            $new_user_id = (int)($stmt->fetchColumn() ?: 0);

            if ($new_user_id > 0) {
                $stmt = $conn_rbe->prepare("UPDATE rbe_users SET fullname=?, phone=?, is_active=1, is_deleted=0 WHERE id=?");
                $stmt->execute([$fullname, $phone, $new_user_id]);
            } else {
                $stmt = $conn_rbe->prepare("INSERT INTO rbe_users (fullname, email, phone, must_set_password, is_active, is_deleted) VALUES (?, ?, ?, 1, 1, 0)");
                $stmt->execute([$fullname, $email, $phone]);
                $new_user_id = (int)$conn_rbe->lastInsertId();
            }

            // Step 2: Ensure landlord role exists
            $stmt = $conn_rbe->prepare("SELECT 1 FROM rbe_roles WHERE user_id=? AND role='landlord'");
            $stmt->execute([$new_user_id]);
            if (!$stmt->fetch()) {
                $stmt = $conn_rbe->prepare("INSERT INTO rbe_roles (user_id, role) VALUES (?, 'landlord')");
                $stmt->execute([$new_user_id]);
            }

            // Step 3: Connect landlord to property
            $stmt = $conn_rbe->prepare("
                UPDATE properties 
                SET landlord_id=? 
                WHERE id=? AND agent_id=?
            ");
            $stmt->execute([$new_user_id, $property_id, $user_id]);

            // Step 4: Generate login token
            $stmt = $conn_rbe->prepare("SELECT token FROM login_tokens WHERE user_id=? AND expires_at > NOW() LIMIT 1");
            $stmt->execute([$new_user_id]);
            $existing_token = $stmt->fetchColumn();

            $tokenToSend = null;
            if (!$existing_token) {
                $token   = bin2hex(random_bytes(32));
                $expires = date('Y-m-d H:i:s', strtotime('+30 minutes'));
                $stmt = $conn_rbe->prepare("INSERT INTO login_tokens (user_id, token, expires_at) VALUES (?, ?, ?)");
                $stmt->execute([$new_user_id, $token, $expires]);
                $tokenToSend = $token;
            }

            $conn_rbe->commit();

            // Step 5: Send email with PHPMailer if token was created
if ($tokenToSend) {
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host       = RBE_SMTP_HOST;
        $mail->SMTPAuth   = true;
        $mail->Username   = RBE_SMTP_USER;
        $mail->Password   = RBE_SMTP_PASS;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = RBE_SMTP_PORT;

        $mail->setFrom(RBE_MAIL_FROM, RBE_MAIL_FROM_NAME);
        $mail->addAddress($email, $fullname);

        $link = RBE_V1_BASE_URL . "/set-password.php?token=" . urlencode($tokenToSend);
        $mail->isHTML(false);
        $mail->Subject = "Set up your RBE landlord account";
        $mail->Body    = "Hi $fullname,\n\nPlease set your password using the link below:\n$link\n\nThis link expires in 30 minutes.";

        $mail->send();
        $flash_ok = "✅ Landlord linked successfully. Email sent to $email.";
    } catch (Exception $e) {
        $flash_ok = "⚠️ Landlord linked successfully, but email failed: {$mail->ErrorInfo}";
    }
} else {
    $flash_ok = "✅ Landlord linked successfully. User already had an active account.";
}

        } catch (PDOException $e) {
            if ($conn_rbe->inTransaction()) $conn_rbe->rollBack();
            $flash_err = "Database error: " . $e->getMessage();
        }
    } else {
        $flash_err = "❌ Full name, email, and property 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 Landlord</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; ?>
  <?php if ($flash_ok): ?><p class="success"><?=$flash_ok?></p><?php endif; ?>

  <form method="post" class="form">
    <label>Full Name:
      <input type="text" name="fullname" required>
    </label>
    <label>Email:
      <input type="email" name="email" required>
    </label>
    <label>Phone:
      <input type="text" name="phone">
    </label>
    <label>Connect 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" name="add_landlord">Save Landlord</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;
}
.success {color:green;font-weight:600;}
.error {color:red;font-weight:600;}
</style>
