<?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') {
    csrfVerify();
    $gmail = trim($_POST['fampay_gmail'] ?? '');
    $appPass = trim($_POST['fampay_app_password'] ?? '');
    // Remove ALL spaces, non-breaking spaces, and any non-alphanumeric chars
    $appPass = preg_replace('/[^a-zA-Z0-9]/', '', $appPass);
    $upi = trim($_POST['fampay_upi_id'] ?? '');

    if (!$gmail || !$appPass || !$upi) {
        $message = 'Please fill in all fields.';
        $messageType = 'error';
    } else {
        // Verify IMAP Connection before saving
        $connResult = connectFamAppGmail($gmail, $appPass);
        
        if ($connResult['success']) {
            @imap_close($connResult['inbox']);
            $user['fampay_gmail'] = $gmail;
            $user['fampay_app_password_encrypted'] = encryptData($appPass);
            $user['fampay_upi_id'] = $upi;
            $user['gmail_connected'] = true;
            saveUser($user);
            $message = 'FamPay Gmail verified and connected successfully!';
            $messageType = 'success';
        } else {
            $rawError = $connResult['error'];
            if (stripos($rawError, 'AUTHENTICATIONFAILED') !== false || stripos($rawError, 'Invalid credentials') !== false) {
                $friendlyError = "Invalid Gmail Address or App Password. Please check your credentials.";
            } else {
                $friendlyError = "Could not connect to Gmail IMAP server. Please try again later.";
            }
            $message = 'Verification Failed: ' . $friendlyError;
            $messageType = 'error';
        }
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'disconnect_gmail') {
    csrfVerify();
    $user['fampay_gmail'] = null;
    $user['fampay_app_password_encrypted'] = null;
    $user['fampay_upi_id'] = null;
    $user['gmail_connected'] = false;
    saveUser($user);
    $message = 'FamPay Gmail disconnected successfully.';
    $messageType = 'success';
}

$canBuyMoreKeys = count($user['api_keys']) < 100;
$decryptedAppPass = $user['gmail_connected'] ? decryptData($user['fampay_app_password_encrypted']) : '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php 
$pageTitle = "Integrations — FamGateway";
include 'includes/header.php'; 
?>
</head>
<body>
<?php include 'includes/nav.php'; ?>
    
<main class="main-content">
    <div class="wrap" style="max-width: 720px;">



    <!-- Page Title -->
    <div class="dash-anim-right" style="margin-bottom: 24px;">
      <h1 style="font-size: 22px; font-weight: 700; color: var(--color-ink); letter-spacing: -0.5px;">
        Integrations
      </h1>
      <p style="font-size: 13px; color: var(--color-ink-mute); margin-top: 4px;">Connect your FamPay Gmail to enable instant automated payment verification.</p>
    </div>

    <!-- GMAIL CONNECTION CARD -->
    <div class="card dash-anim-up">
        <div class="card-header" style="margin-bottom: 20px;">
            <div class="card-title" style="display:flex; align-items:center; gap:10px;">
                <i data-lucide="mail" style="width:18px;height:18px;color:var(--color-primary);"></i> Connect FamPay Gmail
                <span class="badge <?= $user['gmail_connected'] ? 'badge-success' : 'badge-danger' ?>" style="margin-left:auto;">
                    <i data-lucide="<?= $user['gmail_connected'] ? 'check-circle-2' : 'alert-circle' ?>" style="width:12px;height:12px;"></i>
                    <?= $user['gmail_connected'] ? 'Connected' : 'Not Connected' ?>
                </span>
            </div>
            <div class="card-sub">This lets our server automatically read payment notification emails in real-time.</div>
        </div>

        <form method="POST" autocomplete="off" onsubmit="return handleConnect(this);">
            <?php if ($message): ?>
                <div class="callout callout-<?= $messageType === 'success' ? 'success' : 'error' ?>" style="margin-bottom: 20px; font-weight: 500;">
                    <i data-lucide="<?= $messageType === 'success' ? 'check-circle-2' : 'alert-circle' ?>" style="width:16px;height:16px;margin-bottom:-3px;margin-right:4px;"></i>
                    <?= htmlspecialchars($message) ?>
                </div>
            <?php endif; ?>

            <input type="hidden" name="action" value="connect_gmail">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrfToken()) ?>">

            <div class="form-group">
                <label class="form-label">FamPay-linked Gmail Address</label>
                <input type="email" name="fampay_gmail" class="form-input" placeholder="you@gmail.com" value="<?= htmlspecialchars($user['fampay_gmail']) ?>" required autocomplete="off" data-lpignore="true">
            </div>

            <div class="form-group">
                <label class="form-label">Gmail App Password (16-digit)</label>
                <div style="position: relative;">
                    <input type="password" name="fampay_app_password" id="appPassInput" class="form-input" placeholder="xxxx xxxx xxxx xxxx" value="<?= htmlspecialchars($decryptedAppPass) ?>" required autocomplete="new-password" data-lpignore="true" style="padding-right: 40px;">
                    <button type="button" onclick="togglePassword()" style="position: absolute; right: 10px; top: 50%; transform: translateY(-50%); background: none; border: none; cursor: pointer; color: var(--color-ink-mute); padding: 5px;">
                        <i data-lucide="eye" id="eyeIcon" style="width: 18px; height: 18px;"></i>
                    </button>
                </div>
                <div style="font-size: 12px; color: var(--color-ink-mute); margin-top: 6px; line-height: 1.4;">
                    <strong>Important:</strong> Make sure <a href="https://mail.google.com/mail/u/0/#settings/fwdandpop" target="_blank" style="color: var(--color-primary); text-decoration: underline;">IMAP is enabled</a> in your Gmail settings (Settings &gt; Forwarding and POP/IMAP &gt; Enable IMAP).
                </div>
            </div>

            <div class="form-group">
                <label class="form-label">Your FamPay UPI ID</label>
                <input type="text" name="fampay_upi_id" class="form-input" placeholder="username@fam" value="<?= htmlspecialchars($user['fampay_upi_id']) ?>" required>
            </div>

            <button type="submit" class="btn btn-primary" id="saveBtn" style="margin-top:12px; width:100%; padding:12px;"><i data-lucide="check-circle-2" style="width:16px;height:16px;"></i> <?= $user['gmail_connected'] ? 'Update Connection' : 'Verify & Save Connection' ?></button>
        </form>

        <?php if ($user['gmail_connected']): ?>
        <form method="POST" style="margin-top:12px;" onsubmit="return confirm('Are you sure you want to disconnect your Gmail? Automated payment verifications will stop working.');">
            <input type="hidden" name="action" value="disconnect_gmail">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrfToken()) ?>">
            <button type="submit" class="btn btn-danger" style="width:100%; padding:12px; background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; box-shadow: none;"><i data-lucide="trash-2" style="width:16px;height:16px;"></i> Disconnect Gmail</button>
        </form>
        <?php endif; ?>
    </div>

    </div>
</main>
</div>

<script>
function togglePassword() {
    const input = document.getElementById('appPassInput');
    const icon = document.getElementById('eyeIcon');
    if (input.type === 'password') {
        input.type = 'text';
        icon.setAttribute('data-lucide', 'eye-off');
    } else {
        input.type = 'password';
        icon.setAttribute('data-lucide', 'eye');
    }
    if (window.lucide) lucide.createIcons();
}

function handleConnect(form) {
    const btn = form.querySelector('#saveBtn');
    btn.innerHTML = '<i data-lucide="loader-2" class="spin-icon" style="width:16px;height:16px;margin-right:6px;"></i> Verifying...';
    btn.style.opacity = '0.8';
    if(window.lucide) window.lucide.createIcons();
    return true;
}
  if (window.lucide) lucide.createIcons();
</script>
</body>
</html>
