<?php
// wallet/landlord/payouts.php
session_start();
require_once __DIR__ . "/../../db_connect.php";
require_once __DIR__ . "/../includes/wallet_db.php";

if (!isset($_SESSION['user_id'])) {
    exit("Access denied: not logged in.");
}

$current_user_id = (int)$_SESSION['user_id'];
$landlord_id = (int)($_GET['landlord_id'] ?? $current_user_id);

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

if ($role === 'landlord' && $landlord_id !== $current_user_id) {
    exit("Access denied: landlords can only request payouts for themselves.");
}

// Fetch landlord info
$stmt = $conn_rbe->prepare("SELECT fullname FROM rbe_users WHERE id = ?");
$stmt->execute([$landlord_id]);
$landlord_name = $stmt->fetchColumn() ?: "Unknown";

// Balance
$balance = getLandlordBalance($landlord_id, $conn_rbe);

// Handle payout request
$success_msg = $error_msg = "";
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $amount = round((float)($_POST['amount'] ?? 0), 2);

    if ($amount <= 0) {
        $error_msg = "Please enter a valid amount.";
    } elseif ($amount > $balance) {
        $error_msg = "Amount exceeds available balance.";
    } else {
        try {
            $stmt = $conn_rbe->prepare("
                INSERT INTO landlord_wallet_payouts (landlord_id, amount, created_at)
                VALUES (?, ?, NOW())
            ");
            $stmt->execute([$landlord_id, $amount]);

            $success_msg = "Payout request of R " . number_format($amount, 2) . " submitted.";
        } catch (Exception $e) {
            $error_msg = "Error: " . $e->getMessage();
        }
    }
}

// Fetch payout history
// (If `status` column exists, it will be selected too)
$columns = "amount, created_at";
try {
    $check = $conn_rbe->query("SHOW COLUMNS FROM landlord_wallet_payouts LIKE 'status'")->fetch();
    if ($check) {
        $columns .= ", status";
    }
} catch (Exception $e) {}

$stmt = $conn_rbe->prepare("
    SELECT $columns
    FROM landlord_wallet_payouts
    WHERE landlord_id = ?
    ORDER BY created_at DESC
    LIMIT 50
");
$stmt->execute([$landlord_id]);
$requests = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Payout Requests - <?= htmlspecialchars($landlord_name) ?></title>
  <style>
    body { font-family: Arial, sans-serif; background: #051a25; color: #fff; padding: 20px; }
    .card { background: #122c4c; padding: 20px; border-radius: 12px; max-width: 700px; margin: auto; }
    h1 { color: #7ed957; }
    input[type="number"] { padding: 10px; width: 100%; margin: 10px 0; border-radius: 8px; border: none; }
    button { background: #7ed957; color: #000; padding: 10px 20px; border: none; border-radius: 8px; font-weight: bold; cursor: pointer; }
    button:hover { background: #00cc77; }
    table { width: 100%; border-collapse: collapse; margin-top: 15px; }
    th, td { padding: 10px; border: 1px solid #7ed957; text-align: center; }
    th { background: #1b3a4d; color: #7ed957; }
    tr:nth-child(even) { background: #0b1f33; }
    .msg { margin: 10px 0; padding: 10px; border-radius: 8px; }
    .success { background: #1b3a4d; color: #7ed957; }
    .error { background: #3a1b1b; color: #ff7777; }
  </style>
</head>
<body>
  <div class="card">
    <h1>🏦 Payout Requests – <?= htmlspecialchars($landlord_name) ?></h1>

    <p><strong>Available Balance:</strong> R <?= number_format($balance, 2) ?></p>

    <?php if ($success_msg): ?>
      <div class="msg success"><?= htmlspecialchars($success_msg) ?></div>
    <?php elseif ($error_msg): ?>
      <div class="msg error"><?= htmlspecialchars($error_msg) ?></div>
    <?php endif; ?>

    <form method="post">
      <label for="amount">Payout Amount (R):</label>
      <input type="number" name="amount" id="amount" min="1" step="0.01" required>
      <button type="submit">Request Payout</button>
    </form>

    <h2 style="margin-top:20px;">📜 Request History</h2>
    <?php if (empty($requests)): ?>
      <p>No payout requests yet.</p>
    <?php else: ?>
      <table>
        <tr>
          <th>Date</th>
          <th>Amount (R)</th>
          <?php if (isset($requests[0]['status'])): ?>
            <th>Status</th>
          <?php endif; ?>
        </tr>
        <?php foreach ($requests as $r): ?>
          <tr>
            <td><?= htmlspecialchars($r['created_at']) ?></td>
            <td><?= number_format($r['amount'], 2) ?></td>
            <?php if (isset($r['status'])): ?>
              <td><?= htmlspecialchars(ucfirst($r['status'])) ?></td>
            <?php endif; ?>
          </tr>
        <?php endforeach; ?>
      </table>
    <?php endif; ?>

    <p style="margin-top:15px;">
      <a href="../../landlord-dashboard.php" style="color:#7ed957;">⬅ Back to Landlord Dashboard</a>
    </p>
  </div>
</body>
</html>
