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

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

// Release session lock early for faster tab switching
session_write_close();


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

$canBuyMoreKeys = count($user['api_keys']) < 100;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php 
$pageTitle = "Payment Links — FamGateway";
include 'includes/header.php'; 
?>
</head>
<body>
<?php include 'includes/nav.php'; ?>

<main class="main-content">
    <div class="wrap">

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

    <!-- 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;">
        Payment Links
      </h1>
      <p style="font-size: 13px; color: var(--color-ink-mute); margin-top: 4px;">Create and manage custom checkout URLs to share with your customers.</p>
    </div>

    <!-- GENERATE LINK CARD -->
    <?php $isConfigured = ($user['gmail_connected'] == 1 && !empty($user['fampay_upi_id'])); ?>
    <div class="card dash-anim-up">
        <div class="card-header" style="margin-bottom: 16px;">
            <div class="card-title"><i data-lucide="link" style="width:18px;height:18px;color:var(--color-primary);"></i> Generate Payment Link</div>
            <div class="card-sub">Create a custom checkout link to send to your customers manually.</div>
        </div>
        
        <?php if ($isConfigured): ?>
        <div style="display:flex; gap:12px; margin-top:14px; flex-wrap:wrap;">
            <input type="number" id="linkAmount" class="form-input" placeholder="Amount (₹)" style="margin-bottom:0; flex:1; min-width:140px;">
            <input type="text" id="linkSlug" class="form-input" placeholder="Custom URL Slug (optional)" style="margin-bottom:0; flex:2; min-width:200px;">
            <select id="linkExpiry" class="form-input" style="margin-bottom:0; flex:1; min-width:130px;">
                <option value="1m">1 Min</option>
                <option value="5m">5 Mins</option>
                <option value="30m">30 Mins</option>
                <option value="1h">1 Hour</option>
                <option value="2h">2 Hours</option>
                <option value="24h" selected>1 Day</option>
                <option value="72h">3 Days</option>
            </select>
            <button class="btn btn-primary" onclick="createNewPaymentLink()" style="margin-top:0; white-space:nowrap;"><i data-lucide="zap" style="width:15px;height:15px;"></i> Generate</button>
        </div>
        
        <div style="display:none; gap: 12px; align-items: center; flex-wrap: wrap; margin-top: 20px; padding: 14px 18px; border: 1px solid var(--blue-200); background: var(--blue-50); border-radius: var(--r-md);" id="generatedLinkRow">
            <span class="tnum" id="generatedLinkText" style="flex: 1; color: var(--blue-700); font-family: monospace; font-size: 13.5px; font-weight: 500; min-width: 200px; word-break: break-all;"></span>
            <button class="btn btn-secondary btn-sm" onclick="copyText('generatedLinkText', this)"><i data-lucide="copy" style="width:14px;height:14px;"></i> Copy</button>
            <a href="#" target="_blank" class="btn btn-primary btn-sm" id="openLinkBtn" style="margin-top:0;"><i data-lucide="external-link" style="width:14px;height:14px;"></i> Open</a>
        </div>
        <?php else: ?>
        <div style="padding: 24px; text-align: center; background: #fffbeb; border: 1px solid #fde68a; border-radius: var(--r-md); margin-top: 14px;">
            <div style="color: #ca8a04; font-weight: 600; font-size: 14px; margin-bottom: 8px;">
                <i data-lucide="alert-triangle" style="width: 20px; height: 20px; vertical-align: middle; margin-right: 6px;"></i>
                Payment Gateway Not Configured
            </div>
            <div style="color: #854d0e; font-size: 13px; margin-bottom: 16px;">
                Please configure your FamPay IMAP settings to start creating payment links.
            </div>
            <a href="integrations.php" class="btn btn-primary btn-sm">Configure Now</a>
        </div>
        <?php endif; ?>
    </div>

    <!-- MY PAYMENT LINKS CARD -->
    <?php $myLinks = getPaymentLinksByUser($user['id']); ?>
    <div class="card dash-anim-up" style="padding: 0; overflow: hidden; animation-delay: 0.12s;">
        <div style="padding: 22px 28px; border-bottom: 1px solid var(--color-hairline);">
            <div class="card-title"><i data-lucide="list" style="width:18px;height:18px;color:var(--color-primary);"></i> My Payment Links</div>
            <div class="card-sub">Manage your active and expired payment links.</div>
        </div>
        
        <div class="table-container" id="linksTableContainer" style="margin: 0; border-top: none; <?= empty($myLinks) ? 'display:none;' : '' ?>">
            <table class="table">
                <thead>
                    <tr>
                        <th>Link (Slug)</th>
                        <th>Amount</th>
                        <th>Status</th>
                        <th>Created</th>
                        <th style="text-align:right;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($myLinks as $pl): ?>
                    <tr>
                        <td style="font-family: var(--font);">
                            <span style="font-weight: 600; color: var(--color-ink); font-size: 13.5px;"><?= htmlspecialchars($pl['slug']) ?></span>
                            <code style="font-size:11px; color:var(--color-ink-mute); background:var(--surface-page); padding:2px 7px; border-radius:5px; border:1px solid var(--color-hairline); margin-left:8px;">/pay/<?= htmlspecialchars($pl['slug']) ?></code>
                            <div style="display:none;" id="linkUrl_<?= $pl['slug'] ?>"><?= getBaseUrl() ?>/pay/<?= htmlspecialchars($pl['slug']) ?></div>
                        </td>
                        <td class="tnum" style="font-weight: 600; color: var(--color-ink); font-size: 14px;">₹<?= number_format($pl['amount'], 2) ?></td>
                        <td>
                            <?php 
                            if ($pl['status'] === 'pending' && time() > $pl['expires_at']) {
                                $pl['status'] = 'expired';
                                updatePaymentLink($pl['slug'], 'expired');
                            }
                            ?>
                            <?php if($pl['status'] === 'paid'): ?>
                                <span class="badge badge-success" style="padding:4px 10px;"><i data-lucide="check" style="width:12px;height:12px;"></i> Paid</span>
                            <?php elseif($pl['status'] === 'expired'): ?>
                                <span class="badge badge-danger" style="padding:4px 10px;"><i data-lucide="x" style="width:12px;height:12px;"></i> Expired</span>
                            <?php elseif($pl['status'] === 'disabled'): ?>
                                <span class="badge badge-danger" style="padding:4px 10px;"><i data-lucide="ban" style="width:12px;height:12px;"></i> Disabled</span>
                            <?php else: ?>
                                <span class="badge badge-warning" style="padding:4px 10px;"><i data-lucide="clock" style="width:12px;height:12px;"></i> Pending</span>
                            <?php endif; ?>
                        </td>
                        <td class="tnum" style="color: var(--color-ink-secondary); font-size: 12.5px;"><?= date('M d, Y · h:i A', $pl['created_at']) ?></td>
                        <td style="text-align:right; display:flex; gap:8px; justify-content:flex-end;">
                            <button class="btn btn-secondary btn-sm" onclick="copyText('linkUrl_<?= htmlspecialchars($pl['slug'], ENT_QUOTES) ?>', this)"><i data-lucide="copy" style="width:13px;height:13px;"></i> Copy</button>
                            <?php if($pl['status'] === 'pending'): ?>
                                <button class="btn btn-secondary btn-sm" style="color:var(--color-warning-text);" onclick="manageLink('<?= htmlspecialchars($pl['slug'], ENT_QUOTES) ?>', 'expire')"><i data-lucide="clock" style="width:13px;height:13px;"></i> Expire</button>
                            <?php elseif($pl['status'] === 'expired' || $pl['status'] === 'disabled'): ?>
                                <button class="btn btn-secondary btn-sm" style="color:var(--color-success-text);" onclick="manageLink('<?= htmlspecialchars($pl['slug'], ENT_QUOTES) ?>', 'unexpire')"><i data-lucide="refresh-cw" style="width:13px;height:13px;"></i> Reactivate</button>
                            <?php endif; ?>
                            <?php if($pl['status'] !== 'paid' && $pl['status'] !== 'disabled'): ?>
                                <button class="btn btn-danger btn-sm" onclick="manageLink('<?= htmlspecialchars($pl['slug'], ENT_QUOTES) ?>', 'disable')"><i data-lucide="ban" style="width:13px;height:13px;"></i> Disable</button>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <?php if (empty($myLinks)): ?>
        <div class="empty-state" style="padding: 60px 20px;">
            <div class="empty-state-icon"><i data-lucide="link-2-off" style="width:24px;height:24px;"></i></div>
            <div class="empty-state-title">No payment links generated yet</div>
            <div class="empty-state-sub">Create your custom payment link above to get started</div>
        </div>
        <?php endif; ?>
    </div>

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

<script>
    function copyText(elId, btn) {
        const text = document.getElementById(elId).innerText;
        navigator.clipboard.writeText(text).then(() => {
            const old = btn.innerHTML;
            btn.innerHTML = '<i data-lucide="check" style="width:13px;height:13px;vertical-align:text-bottom;margin-right:4px;"></i> Copied!';
            if(window.lucide) window.lucide.createIcons();
            setTimeout(() => { btn.innerHTML = old; if(window.lucide) window.lucide.createIcons(); }, 1500);
        });
    }

    function createNewPaymentLink() {
        const amt = document.getElementById('linkAmount').value;
        const slug = document.getElementById('linkSlug').value.trim();
        const expiry = document.getElementById('linkExpiry').value;
        
        if (!amt || isNaN(amt) || amt <= 0) {
            alert('Please enter a valid amount greater than 0.');
            return;
        }

        const fd = new FormData();
        fd.append('action', 'create');
        fd.append('amount', amt);
        fd.append('slug', slug);
        fd.append('expiry', expiry);
        fd.append('csrf_token', '<?= htmlspecialchars(csrfToken()) ?>');

        fetch('api/manage-links.php', { method: 'POST', body: fd })
            .then(res => res.json())
            .then(data => {
                if (data.status === 'success') {
                    window.location.reload();
                } else {
                    alert(data.message || 'Error creating link');
                }
            })
            .catch(() => alert('Network error'));
    }

    function manageLink(slug, action) {
        if (action === 'disable' && !confirm('Are you sure you want to disable this payment link?')) return;
        if (action === 'expire' && !confirm('Expire this link immediately?')) return;
        if (action === 'unexpire' && !confirm('Reactivate/Unexpire this payment link for 24 hours?')) return;

        const fd = new FormData();
        fd.append('action', action);
        fd.append('slug', slug);
        fd.append('csrf_token', '<?= htmlspecialchars(csrfToken()) ?>');

        fetch('api/manage-links.php', { method: 'POST', body: fd })
            .then(res => res.json())
            .then(data => {
                if (data.status === 'success') {
                    window.location.reload();
                } else {
                    alert(data.message || 'Error managing link');
                }
            })
            .catch(() => alert('Network error'));
    }
</script>

<script>
  if (window.lucide) lucide.createIcons();
</script>
</body>
</html>
