<?php
/**
 * EdumacFlo SaaS — Payment Return & Callback Handler
 */
if (session_status() === PHP_SESSION_NONE) session_start();
require_once dirname(__DIR__) . '/admin/inc/master_db.php';
require_once dirname(__DIR__) . '/lib/SubscriptionManager.php';
require_once dirname(__DIR__) . '/lib/PaymentGateway.php';

$masterConn = get_master_connection();
$subMgr     = new SubscriptionManager($masterConn);
$gateway    = new PaymentGateway();

$reference = trim($_GET['reference'] ?? $_GET['trxref'] ?? '');
$gw        = trim($_GET['gateway'] ?? 'paystack');

$success   = false;
$errorMsg  = null;
$receipt   = null;

if (empty($reference)) {
    $errorMsg = 'No transaction reference found in callback request.';
} else {
    // Check if transaction already processed (idempotency)
    $stmt = $masterConn->prepare("SELECT s.*, t.school_name, t.slug, p.name AS plan_name FROM `saas_subscriptions` s JOIN `tenants` t ON s.tenant_id = t.id LEFT JOIN `saas_plans` p ON s.plan_id = p.id WHERE s.transaction_ref = ? LIMIT 1");
    $stmt->bind_param("s", $reference);
    $stmt->execute();
    $existing = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($existing) {
        $success = true;
        $receipt = [
            'transaction_ref' => $existing['transaction_ref'],
            'school_name'     => $existing['school_name'],
            'slug'            => $existing['slug'],
            'plan_name'       => $existing['plan_name'],
            'amount'          => $existing['amount_paid'],
            'currency'        => $existing['currency'],
            'cycle'           => $existing['billing_cycle'],
            'expiry_date'     => $existing['expiry_date'],
            'paid_at'         => $existing['created_at'],
        ];
    } else {
        // Verify transaction with gateway
        $verifyRes = $gateway->verifyTransaction($reference, $gw);

        if (!empty($verifyRes['success'])) {
            // Determine tenant and plan details
            $tenantId = (int)($_GET['tenant_id'] ?? $verifyRes['metadata']['tenant_id'] ?? 0);
            $planId   = (int)($_GET['plan_id'] ?? $verifyRes['metadata']['plan_id'] ?? 0);
            $cycle    = in_array($_GET['cycle'] ?? $verifyRes['metadata']['billing_cycle'] ?? '', ['termly', 'sessionally', 'monthly', 'annually'], true) ? ($_GET['cycle'] ?? $verifyRes['metadata']['billing_cycle']) : 'sessionally';
            $amount   = (float)($verifyRes['amount'] ?? $_GET['amount'] ?? 0);

            if (!$tenantId) {
                // Fallback: lookup by session
                $slug = $_SESSION['renew_tenant_slug'] ?? '';
                if ($slug) {
                    $ts = $masterConn->prepare("SELECT id FROM `tenants` WHERE `slug` = ? LIMIT 1");
                    $ts->bind_param("s", $slug);
                    $ts->execute();
                    $tRow = $ts->get_result()->fetch_assoc();
                    $ts->close();
                    if ($tRow) $tenantId = (int)$tRow['id'];
                }
            }

            if (!$tenantId || !$planId) {
                $errorMsg = 'Payment verified, but tenant or plan identifier was missing in session metadata.';
            } else {
                $actRes = $subMgr->activateSubscription(
                    $tenantId,
                    $planId,
                    $cycle,
                    $amount,
                    $gw,
                    $reference,
                    'active'
                );

                if ($actRes['success']) {
                    $success = true;
                    $receipt = [
                        'transaction_ref' => $reference,
                        'school_name'     => $actRes['tenant']['school_name'],
                        'slug'            => $actRes['tenant']['slug'],
                        'plan_name'       => $actRes['plan']['name'],
                        'amount'          => $amount,
                        'currency'        => 'NGN',
                        'cycle'           => $cycle,
                        'expiry_date'     => $actRes['expiry_date'],
                        'paid_at'         => date('Y-m-d H:i:s'),
                    ];
                } else {
                    $errorMsg = $actRes['message'];
                }
            }
        } else {
            $errorMsg = $verifyRes['message'] ?? 'Payment verification was rejected by gateway.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Receipt — EdumacFlo</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg: #0d1117;
            --card-bg: #161b22;
            --border: #30363d;
            --accent: #2563eb;
            --green: #3fb950;
            --red: #f85149;
            --text: #e6edf3;
            --text-muted: #8b949e;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: var(--bg);
            color: var(--text);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .receipt-card {
            background: var(--card-bg);
            border: 1px solid var(--border);
            border-radius: 12px;
            max-width: 520px;
            width: 100%;
            padding: 32px;
            box-shadow: 0 10px 30px rgba(0,0,0,.5);
        }
        .icon-header {
            text-align: center;
            margin-bottom: 20px;
        }
        .icon-circle {
            width: 58px; height: 58px;
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 12px;
            font-size: 1.8rem;
        }
        .icon-circle.success { background: rgba(63,185,80,.15); color: var(--green); border: 1px solid rgba(63,185,80,.3); }
        .icon-circle.failed  { background: rgba(248,81,73,.15); color: var(--red); border: 1px solid rgba(248,81,73,.3); }
        h1 { font-size: 1.4rem; font-weight: 700; color: #fff; text-align: center; margin-bottom: 6px; }
        p.sub { text-align: center; color: var(--text-muted); font-size: .88rem; margin-bottom: 24px; }
        
        .receipt-table { width: 100%; border-collapse: collapse; margin-bottom: 24px; font-size: .88rem; }
        .receipt-table tr { border-bottom: 1px solid var(--border); }
        .receipt-table td { padding: 10px 0; }
        .receipt-table td.label { color: var(--text-muted); }
        .receipt-table td.val { text-align: right; font-weight: 600; color: #fff; }
        .receipt-table td.val.mono { font-family: monospace; font-size: .82rem; }

        .btn-return {
            display: block;
            width: 100%;
            text-align: center;
            background: var(--accent);
            color: #fff;
            padding: 12px;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 600;
            font-size: .92rem;
            transition: background .15s;
        }
        .btn-return:hover { background: #1d4ed8; }
        .btn-retry {
            display: block;
            width: 100%;
            text-align: center;
            background: #21262d;
            border: 1px solid var(--border);
            color: #fff;
            padding: 12px;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 600;
            font-size: .92rem;
        }
    </style>
</head>
<body>
<div class="receipt-card">
    <?php if ($success && $receipt): ?>
        <div class="icon-header">
            <div class="icon-circle success">✓</div>
            <h1>Subscription Activated!</h1>
            <p class="sub">Thank you. Your school subscription has been renewed successfully.</p>
        </div>

        <table class="receipt-table">
            <tr>
                <td class="label">School</td>
                <td class="val"><?= htmlspecialchars($receipt['school_name']) ?></td>
            </tr>
            <tr>
                <td class="label">Plan Tier</td>
                <td class="val"><?= htmlspecialchars($receipt['plan_name']) ?> (<?= ucfirst($receipt['cycle']) ?>)</td>
            </tr>
            <tr>
                <td class="label">Amount Paid</td>
                <td class="val" style="color:var(--green)">₦<?= number_format($receipt['amount'], 2) ?></td>
            </tr>
            <tr>
                <td class="label">Reference</td>
                <td class="val mono"><?= htmlspecialchars($receipt['transaction_ref']) ?></td>
            </tr>
            <tr>
                <td class="label">Payment Date</td>
                <td class="val"><?= htmlspecialchars($receipt['paid_at']) ?></td>
            </tr>
            <tr>
                <td class="label">New Expiration Date</td>
                <td class="val" style="color:#93c5fd"><?= htmlspecialchars(substr($receipt['expiry_date'], 0, 10)) ?></td>
            </tr>
        </table>

        <a href="../../login.php" class="btn-return">Access School Portal</a>
    <?php else: ?>
        <div class="icon-header">
            <div class="icon-circle failed">✗</div>
            <h1>Payment Incomplete</h1>
            <p class="sub"><?= htmlspecialchars($errorMsg ?? 'We were unable to verify your payment.') ?></p>
        </div>

        <a href="renew.php" class="btn-retry">Back to Renewal Options</a>
    <?php endif; ?>
</div>
</body>
</html>
