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

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

$isExpired = strtotime($user['plan_expires_at']) <= time();
$userLinks = getShortlinksByUser($user['id']);

$pageTitle = 'Payment Links';
$activeNav = 'payment_links';
include __DIR__ . '/includes/user_header.php';
?>

<div class="page-head">
  <h1 class="page-title">Payment links</h1>
  <p class="page-sub">Create a short checkout link that takes your customer straight to a payment page. Each link lives for 10 minutes.</p>
</div>

<?php if ($isExpired): ?>
  <div class="alert alert-warn">
    <strong>Your plan has expired.</strong> Please <a href="plans.php" style="font-weight:600; text-decoration:underline;">renew your plan</a> to keep using payment links.
  </div>
<?php endif; ?>

<?php if (empty($user['api_keys'])): ?>
  <div class="alert alert-warn">
    <strong>You need an API key first.</strong> <a href="api_keys.php" style="font-weight:600; text-decoration:underline;">Create one here →</a>
  </div>
<?php endif; ?>

<?php if (!$user['gmail_connected']): ?>
  <div class="alert alert-warn">
    <strong>Connect your FamPay Gmail first.</strong> <a href="integrations.php" style="font-weight:600; text-decoration:underline;">Connect here →</a>
  </div>
<?php endif; ?>

<div class="card">
  <h2 class="card-title">Create a new link</h2>
  <div class="grid2">
    <div>
      <label class="label" for="plAmount">Amount (₹)</label>
      <input class="input" type="number" id="plAmount" min="1" step="0.01" placeholder="e.g. 99">
    </div>
    <div>
      <label class="label" for="plName">Link name (optional)</label>
      <input class="input" type="text" id="plName" maxlength="60" placeholder="e.g. Order #482">
    </div>
  </div>
  <div>
    <label class="label" for="plRedirect">Redirect URL after payment (optional)</label>
    <input class="input" type="text" id="plRedirect" placeholder="https://yourstore.com/thank-you">
  </div>
  <div class="row mt-24">
    <button class="btn btn-primary" id="plCreateBtn" onclick="createPayLink()">Create link</button>
  </div>
</div>

<div class="card">
  <h2 class="card-title">Your links (<?= count($userLinks) ?>)</h2>
  <div class="card-sub">Each link expires 10 minutes after creation. Clicks are counted every time the link is opened.</div>
  <?php if (count($userLinks) === 0): ?>
    <p style="font-size:14px; color:var(--muted); margin-top:12px;">No payment links yet. Create your first one above.</p>
  <?php else: ?>
    <?php foreach ($userLinks as $lIdx => $link): ?>
      <?php
        $fullUrl = getBaseUrl() . '/s.php?c=' . urlencode($link['code']);
        $isLinkExpired = isShortlinkExpired($link);
      ?>
      <div class="key-row">
        <span class="key-text" id="payLinkText<?= $lIdx ?>"><?= htmlspecialchars($fullUrl) ?></span>
        <button class="btn btn-secondary btn-sm" onclick="copyText('payLinkText<?= $lIdx ?>', this)">Copy</button>
        <a class="btn btn-outline btn-sm" href="<?= htmlspecialchars($fullUrl) ?>" target="_blank" rel="noopener">Open</a>
      </div>
      <div class="key-label" style="margin-top:10px">
        <?php if (!empty($link['target_url'])): ?>
          <div class="code-block" style="margin:6px 0">
            <div class="code-label">Full URL <button class="copy-btn" onclick="copyText('payLinkTarget<?= $lIdx ?>', this)">Copy</button></div>
            <pre id="payLinkTarget<?= $lIdx ?>" style="font-size:11.5px;line-height:1.6;word-break:break-all;white-space:pre-wrap"><?= htmlspecialchars($link['target_url']) ?></pre>
          </div>
        <?php endif; ?>
        <div style="display:flex;gap:12px;flex-wrap:wrap;font-size:12.5px;color:var(--muted);margin-top:6px">
          <span>Clicks: <strong style="color:var(--ink)"><?= (int)$link['clicks'] ?></strong></span>
          <span>·</span>
          <span><?= $isLinkExpired ? '<span style="color:var(--down);">Expired</span>' : 'Valid till ' . date('h:i A', (int)$link['expires_at_timestamp']) ?></span>
        </div>
      </div>
      <?php if ($lIdx < count($userLinks) - 1): ?><div class="divider"></div><?php endif; ?>
    <?php endforeach; ?>
  <?php endif; ?>
</div>

<div class="card" style="background:var(--surface-soft); border-style:dashed;">
  <h2 class="card-title">How it works</h2>
  <p style="font-size:14px; color:var(--body); line-height:1.7;">
    Enter an amount and we build a checkout URL with your own API key, then wrap it in a short
    <span class="mono"><?= htmlspecialchars(getBaseUrl()) ?>/s.php?c=XXXXXX</span> link.
    When someone opens it, they are redirected to the payment page — and the click counter increments here.
  </p>
</div>

<script>
    function copyText(elId, btn) {
        const text = document.getElementById(elId).innerText;
        navigator.clipboard.writeText(text).then(() => {
            const old = btn.innerText;
            btn.innerText = 'Copied';
            setTimeout(() => btn.innerText = old, 1500);
        });
    }

    function createPayLink() {
        const amount = parseFloat(document.getElementById('plAmount').value);
        if (!amount || amount <= 0) { alert('Please enter a valid amount.'); return; }

        const btn = document.getElementById('plCreateBtn');
        btn.disabled = true;
        btn.innerText = 'Creating…';

        encryptedFetch('api/create_payment_link.php', {
            amount: amount,
            name: document.getElementById('plName').value.trim(),
            redirect_url: document.getElementById('plRedirect').value.trim()
        }).then(data => {
            btn.disabled = false;
            btn.innerText = 'Create link';
            if (data.status === 'success') {
                alert('Link created! It is valid for 10 minutes.');
                window.location.reload();
            } else {
                alert(data.message || 'Something went wrong.');
            }
        }).catch(() => {
            btn.disabled = false;
            btn.innerText = 'Create link';
            alert('Connection error. Please try again.');
        });
    }
</script>

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