<?php
require_once __DIR__ . '/includes/functions.php';
startSecureSession();
requireLogin();

$user = getUserById($_SESSION['user_id']);
if (!$user) {
    header('Location: logout.php');
    exit;
}

$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'connect_gmail') {
    if (!empty($user['gmail_connected'])) {
        $message = 'Already connected. Delete the existing connection first if you want to change it.';
        $messageType = 'error';
    } else {
        $gmail = trim($_POST['fampay_gmail'] ?? '');
        $appPass = trim($_POST['fampay_app_password'] ?? '');
        $upi = trim($_POST['fampay_upi_id'] ?? '');

        if (!$gmail || !$appPass || !$upi) {
            $message = 'Please fill in all fields.';
            $messageType = 'error';
        } elseif (!preg_match('/^[a-zA-Z0-9._%+-]+@gmail\.com$/i', $gmail)) {
            $message = 'Please enter a valid Gmail address (example: you@gmail.com).';
            $messageType = 'error';
        } else {
            // Real-time IMAP validation — only connect if credentials actually work
            $inbox = @imap_open('{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX', $gmail, $appPass, 0, 1);
            if (!$inbox) {
                $inbox = @imap_open('{imap.gmail.com:993/imap/ssl}INBOX', $gmail, $appPass, 0, 1);
            }
            if ($inbox) {
                imap_close($inbox);
                $user['fampay_gmail'] = $gmail;
                $user['fampay_app_password_encrypted'] = encryptData($appPass);
                $user['fampay_upi_id'] = $upi;
                $user['gmail_connected'] = true;
                saveUser($user);
                $message = 'Gmail verified and connected! Payment auto-detection is now active.';
                $messageType = 'success';
            } else {
                $error = imap_last_error() ?: 'Could not connect to Gmail. Check your email and app password.';
                $message = 'Gmail connection failed: ' . $error . '. Please verify your email and app password are correct.';
                $messageType = 'error';
            }
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'disconnect_gmail') {
    $user['fampay_gmail'] = '';
    $user['fampay_app_password_encrypted'] = '';
    $user['fampay_upi_id'] = '';
    $user['gmail_connected'] = false;
    saveUser($user);
    $message = 'Connection removed. You can connect a new account below.';
    $messageType = 'success';
}

$pageTitle = 'Gmail & Settings';
$activeNav = 'integrations';
include __DIR__ . '/includes/user_header.php';
?>

<div class="page-head">
  <h1 class="page-title">Gmail &amp; settings</h1>
  <p class="page-sub">Connect the Gmail linked to your FamPay account so we can verify your incoming payments automatically.</p>
</div>

<?php if ($message): ?>
  <div class="alert alert-<?= $messageType === 'success' ? 'ok' : 'warn' ?>"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>

<div class="card">
  <div class="justify-between flex flex-wrap items-center" style="gap:16px;">
    <div>
      <h2 class="card-title">FamPay Gmail connection</h2>
      <div class="card-sub" style="margin-bottom:0;">
        <?= $user['gmail_connected']
            ? 'Connected to <span class="mono">' . htmlspecialchars($user['fampay_gmail']) . '</span>'
            : 'Not connected yet' ?>
      </div>
    </div>
    <span class="badge <?= $user['gmail_connected'] ? 'badge-green' : 'badge-gray' ?>">
      <?= $user['gmail_connected'] ? 'Connected' : 'Not connected' ?>
    </span>
  </div>
</div>

<?php if ($user['gmail_connected']): ?>
  <div class="card">
    <h2 class="card-title">Manage connection</h2>
    <p style="font-size:14px; color:var(--body); line-height:1.7; margin-bottom:18px;">
      Your connection is live. If your FamPay account details change, delete this connection and re-enter the new details.
    </p>
    <form method="POST" onsubmit="return confirm('Delete this connection? You will need to re-enter your Gmail, app password, and UPI ID to reconnect.');">
      <input type="hidden" name="action" value="disconnect_gmail">
      <button type="submit" class="btn btn-danger">Delete connection</button>
    </form>
  </div>
<?php else: ?>
  <div class="card">
    <h2 class="card-title">Connect your account</h2>
    <div class="card-sub">These details are encrypted and only used to watch for payment confirmations.</div>
    <form method="POST" style="margin-top:16px;">
      <input type="hidden" name="action" value="connect_gmail">

      <label class="label" for="fgGmail">FamPay-linked Gmail address</label>
      <input class="input" type="email" id="fgGmail" name="fampay_gmail" placeholder="you@gmail.com" required>

      <label class="label" for="fgAppPass">Gmail app password (16-digit)</label>
      <input class="input" type="password" id="fgAppPass" name="fampay_app_password" placeholder="Enter app password" required>

      <label class="label" for="fgUpi">Your FamPay UPI ID</label>
      <input class="input" type="text" id="fgUpi" name="fampay_upi_id" placeholder="yourname@fam" required>

      <div class="row mt-24">
        <button type="submit" class="btn btn-primary">Save connection</button>
      </div>
    </form>
  </div>
<?php endif; ?>

<div class="card" style="background:var(--surface-soft); border-style:dashed;">
  <h2 class="card-title">How to get an app password</h2>
  <ol style="font-size:14px; color:var(--body); line-height:1.9; padding-left:18px; margin:0;">
    <li>Open your Google account → <strong>Security</strong> → <strong>2-Step Verification</strong> (enable it if off).</li>
    <li>Go to <strong>App passwords</strong> and create one for <strong>Mail</strong>.</li>
    <li>Copy the generated 16-character password into the field above.</li>
    <li>Enter the UPI ID exactly as shown in your FamPay app (e.g. <span class="mono">yourname@fam</span>).</li>
  </ol>
</div>

<?php include __DIR__ . '/includes/user_footer.php'; ?>
