<?php
/**
 * payment_success.php
 * Unified success page for PayPal, Stripe, Razorpay.
 * GET: ?session_id=XXX&tracking_code=XXX&method=stripe|paypal|razorpay
 */
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/inc/payment_helpers.php';
require_once __DIR__ . '/lib/stripe-php/init.php';

\Stripe\Stripe::setApiKey(STRIPE_SECRET_KEY);

$session_id    = trim($_GET['session_id']    ?? '');
$tracking_code = trim($_GET['tracking_code'] ?? '');
$method        = strtolower(trim($_GET['method'] ?? 'stripe'));

if (!$session_id || !$tracking_code) {
    renderError('Missing payment confirmation parameters.'); exit;
}

$payment_details = null;
$submission_info = null;
$error           = '';

try {
    // ── Stripe: retrieve and save if not yet recorded ─────────────────────────
    if ($method === 'stripe') {
        $cs = \Stripe\Checkout\Session::retrieve($session_id);

        if ($cs->payment_status !== 'paid') {
            throw new RuntimeException('Payment not completed. Status: ' . $cs->payment_status);
        }

        $pi = \Stripe\PaymentIntent::retrieve($cs->payment_intent);

        // Idempotent insert
        $ex = db()->prepare("SELECT payment_id FROM payments WHERE BINARY gateway_session_id = ? LIMIT 1");
        $ex->execute([$session_id]);
        if (!$ex->fetch()) {
            $sub_stmt = db()->prepare("SELECT submission_id FROM submissions WHERE BINARY tracking_code = ? LIMIT 1");
            $sub_stmt->execute([$tracking_code]);
            $sub = $sub_stmt->fetch(PDO::FETCH_ASSOC);

            $payer_email = $cs->customer_details->email ?? $cs->customer_email ?? '';
            $payer_name  = $cs->customer_details->name  ?? '';
            $amt         = $cs->amount_total / 100;
            $cur         = strtoupper($cs->currency);

            db()->prepare("
                INSERT INTO payments
                    (submission_id, tracking_code, invoice_no, gateway,
                     gateway_session_id, gateway_capture_id, status,
                     payer_email, payer_name, amount, currency, raw_response, paid_at)
                VALUES (?, ?, ?, 'stripe', ?, ?, 'COMPLETED', ?, ?, ?, ?, ?, NOW())
            ")->execute([
                $sub['submission_id'] ?? null,
                $tracking_code,
                'CGBL-' . $tracking_code,
                $session_id,
                $pi->id,
                $payer_email,
                $payer_name,
                $amt,
                $cur,
                json_encode(['session' => $cs->toArray(), 'intent' => $pi->toArray()]),
            ]);
        }

        // Refresh from DB for display
        $row = db()->prepare("SELECT * FROM payments WHERE BINARY gateway_session_id = ? LIMIT 1");
        $row->execute([$session_id]);
        $p = $row->fetch(PDO::FETCH_ASSOC);

    } else {
        // PayPal / Razorpay — already saved by their capture endpoints
        $row = db()->prepare("
            SELECT * FROM payments
            WHERE (BINARY gateway_order_id = ? OR BINARY gateway_capture_id = ? OR BINARY gateway_session_id = ?)
              AND tracking_code = ?
            ORDER BY payment_id DESC LIMIT 1
        ");
        $row->execute([$session_id, $session_id, $session_id, $tracking_code]);
        $p = $row->fetch(PDO::FETCH_ASSOC);
        if (!$p) { throw new RuntimeException('Payment record not found.'); }
    }

    if ($p) {
        $payment_details = [
            'tracking_code' => $p['tracking_code'],
            'invoice_no'    => $p['invoice_no'],
            'amount'        => number_format((float)$p['amount'], 2),
            'currency'      => $p['currency'],
            'symbol'        => getCurrencySymbol($p['currency']),
            'gateway'       => ucfirst($p['gateway']),
            'capture_id'    => $p['gateway_capture_id'] ?? $p['gateway_session_id'],
            'payer_email'   => $p['payer_email'] ?? '',
            'payer_name'    => $p['payer_name']  ?? '',
            'status'        => $p['status'],
            'paid_at'       => $p['paid_at'] ?? date('Y-m-d H:i:s'),
        ];
    }

    // Ensure submission is marked as paid
    db()->prepare("UPDATE submissions SET submission_status = 'submitted' WHERE BINARY tracking_code = ?")
        ->execute([$tracking_code]);

    // Fetch submission info for next-steps
    $si = db()->prepare("
        SELECT s.submission_id, mi.article_title, j.name AS journal_name
        FROM submissions s
        LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
        LEFT JOIN journals j         ON j.journal_id     = s.journal_id
        WHERE BINARY s.tracking_code = ? LIMIT 1
    ");
    $si->execute([$tracking_code]);
    $submission_info = $si->fetch(PDO::FETCH_ASSOC);

} catch (Throwable $e) {
    logPaymentError('Success page error: ' . $e->getMessage(), $tracking_code);
    $error = $e->getMessage();
}

$pageTitle  = 'Payment Successful';
$activePage = 'payment';
$_layout = file_exists(__DIR__ . '/_layout.php')
    ? __DIR__ . '/_layout.php'
    : (file_exists(__DIR__ . '/../_layout.php') ? __DIR__ . '/../_layout.php' : null);
if ($_layout) {
    require_once $_layout;
} else {
    echo '<!doctype html><html lang="en"><head><meta charset="utf-8">'
       . '<meta name="viewport" content="width=device-width,initial-scale=1">'
       . '<title>' . htmlspecialchars($pageTitle) . '</title>'
       . '<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">'
       . '<style>'
       . ':root{--white:#fff;--border:#e2e8f0;--muted:#64748b;--teal:#14b8a6;--teal-dk:#0f9488;--font:"Inter",sans-serif}'
       . '*{box-sizing:border-box;margin:0;padding:0}'
       . 'body{font-family:var(--font);background:#f8fafc;color:#1e293b;min-height:100vh}'
       . '.au-main{max-width:700px;margin:0 auto;padding:30px 20px}'
       . '</style></head><body><div class="au-main">';
}
?>

<style>
.success-wrap  { max-width: 640px; margin: 0 auto; }
.success-hero  { text-align: center; padding: 32px 20px 24px; }
.success-icon  { width: 72px; height: 72px; background: #16a34a; border-radius: 50%; margin: 0 auto 16px; display: flex; align-items: center; justify-content: center; }
.success-icon svg { color: #fff; }
.success-title { font-size: 22px; font-weight: 800; color: #15803d; }
.success-sub   { font-size: 14px; color: var(--muted); margin-top: 6px; }
.receipt-card  { background: var(--white); border: 1px solid var(--border); border-radius: 10px; padding: 24px; margin-bottom: 18px; }
.receipt-hdr   { font-size: 13.5px; font-weight: 700; margin-bottom: 14px; color: #1e293b; border-bottom: 1px solid var(--border); padding-bottom: 10px; }
.receipt-row   { display: flex; justify-content: space-between; align-items: flex-start; padding: 7px 0; border-bottom: 1px solid #f1f5f9; font-size: 13px; }
.receipt-row:last-child { border-bottom: none; }
.receipt-label { color: var(--muted); }
.receipt-val   { font-weight: 600; text-align: right; max-width: 60%; word-break: break-all; }
.status-ok     { color: #16a34a; font-weight: 700; }
.steps-card    { background: #fffbeb; border: 1px solid #fde68a; border-radius: 10px; padding: 20px; margin-bottom: 18px; }
.steps-card h4 { font-size: 13.5px; font-weight: 700; margin-bottom: 12px; color: #78350f; }
.steps-card ul { padding-left: 18px; font-size: 13px; color: #78350f; line-height: 1.8; }
.action-row    { display: flex; gap: 10px; flex-wrap: wrap; }
.btn-action    { flex: 1; min-width: 140px; padding: 12px; border-radius: 8px; font-size: 13.5px; font-weight: 700; text-align: center; cursor: pointer; border: none; font-family: var(--font); text-decoration: none; display: flex; align-items: center; justify-content: center; gap: 6px; }
.btn-primary   { background: var(--teal); color: #fff; }
.btn-primary:hover { background: var(--teal-dk); }
.btn-secondary { background: var(--white); color: #1e293b; border: 1.5px solid var(--border); }
.btn-secondary:hover { background: #f8fafc; }
.error-card { background: #fee2e2; border: 1px solid #fca5a5; border-radius: 10px; padding: 20px; margin-bottom: 18px; color: #991b1b; font-size: 13px; }
</style>

<div class="success-wrap">

<?php if ($payment_details && !$error): ?>

  <div class="success-hero">
    <div class="success-icon">
      <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3">
        <polyline points="20 6 9 17 4 12"/>
      </svg>
    </div>
    <div class="success-title">Payment Successful!</div>
    <div class="success-sub">Your publication fee has been received. Keep this page as your receipt.</div>
  </div>

  <!-- Receipt -->
  <div class="receipt-card">
    <div class="receipt-hdr">🧾 Payment Receipt</div>
    <div class="receipt-row">
      <span class="receipt-label">Tracking Code</span>
      <span class="receipt-val"><?= htmlspecialchars($payment_details['tracking_code']) ?></span>
    </div>
    <div class="receipt-row">
      <span class="receipt-label">Invoice No.</span>
      <span class="receipt-val"><?= htmlspecialchars($payment_details['invoice_no']) ?></span>
    </div>
    <div class="receipt-row">
      <span class="receipt-label">Amount Paid</span>
      <span class="receipt-val"><?= $payment_details['symbol'] . $payment_details['amount'] . ' ' . $payment_details['currency'] ?></span>
    </div>
    <div class="receipt-row">
      <span class="receipt-label">Payment Method</span>
      <span class="receipt-val"><?= htmlspecialchars($payment_details['gateway']) ?></span>
    </div>
    <div class="receipt-row">
      <span class="receipt-label">Transaction ID</span>
      <span class="receipt-val"><?= htmlspecialchars($payment_details['capture_id'] ?? '—') ?></span>
    </div>
    <?php if ($payment_details['payer_email']): ?>
    <div class="receipt-row">
      <span class="receipt-label">Payer Email</span>
      <span class="receipt-val"><?= htmlspecialchars($payment_details['payer_email']) ?></span>
    </div>
    <?php endif; ?>
    <div class="receipt-row">
      <span class="receipt-label">Date</span>
      <span class="receipt-val"><?= date('d M Y, H:i', strtotime($payment_details['paid_at'])) ?></span>
    </div>
    <div class="receipt-row">
      <span class="receipt-label">Status</span>
      <span class="receipt-val status-ok">✓ COMPLETED</span>
    </div>
    <?php if ($submission_info['article_title'] ?? ''): ?>
    <div class="receipt-row">
      <span class="receipt-label">Article</span>
      <span class="receipt-val"><?= htmlspecialchars($submission_info['article_title']) ?></span>
    </div>
    <?php endif; ?>
    <?php if ($submission_info['journal_name'] ?? ''): ?>
    <div class="receipt-row">
      <span class="receipt-label">Journal</span>
      <span class="receipt-val"><?= htmlspecialchars($submission_info['journal_name']) ?></span>
    </div>
    <?php endif; ?>
  </div>

  <!-- Next steps -->
  <div class="steps-card">
    <h4>⚠ Next Steps — Action Required</h4>
    <ul>
      <li>Download this receipt (screenshot or PDF button below).</li>
      <li>Upload your <strong>Author Declaration</strong> form.</li>
      <li>Upload your <strong>Final Manuscript</strong> (camera-ready PDF).</li>
      <li>Upload this <strong>Payment Receipt</strong> as proof.</li>
      <li>Submit all via the Final Submission System.</li>
    </ul>
  </div>

  <!-- Action buttons -->
  <div class="action-row">
    <button class="btn-action btn-primary" onclick="printReceipt()">
      <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
      Print Receipt
    </button>
    <a href="dashboard.php" class="btn-action btn-secondary">
      <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>
      Back to Dashboard
    </a>
  </div>

<?php else: ?>

  <div class="error-card">
    <strong>⚠ Payment Status Unknown</strong>
    <p style="margin-top:8px"><?= htmlspecialchars($error ?: 'Could not retrieve payment details.') ?></p>
    <p style="margin-top:8px">Tracking code: <strong><?= htmlspecialchars($tracking_code) ?></strong><br>
    Contact <a href="mailto:editorialoffice@communeglobal.com">editorialoffice@communeglobal.com</a> with these details.</p>
  </div>
  <a href="dashboard.php" class="btn-action btn-secondary" style="display:inline-flex;width:auto;padding:10px 20px;text-decoration:none;border-radius:8px">← Back to Dashboard</a>

<?php endif; ?>

</div>

<script>
function printReceipt() { window.print(); }
</script>

<?php
if (function_exists('layoutEnd')) {
    layoutEnd();
} else {
    echo '</div></body></html>';
}
?>