<?php
require_once 'config.php';
require 'fpdf/fpdf.php';

function formatReceiptNumber($id) {
    return 'RCT-' . date('Y') . '-' . str_pad($id, 3, '0', STR_PAD_LEFT);
}

function formatPhoneDisplay(?string $phone): string
{
    if (!$phone) {
        return '-';
    }

    $phone = preg_replace('/\s+/', '', $phone);

    if (preg_match('/^254(7\d{8})$/', $phone, $m)) {
        return '0' . $m[1];
    }

    if (preg_match('/^254(1\d{8})$/', $phone, $m)) {
        return '0' . $m[1];
    }

    return $phone;
}

try {
    // Always fetch the most recent transaction logically
    $stmt = $pdo->query("
        SELECT *
        FROM mpesa_payments
        ORDER BY created_at DESC
        LIMIT 1
    ");
    $txn = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    die("Error loading receipt.");
}

if (!$txn) {
    die("No transaction found.");
}

/*
|--------------------------------------------------------------------------
| SINGLE SOURCE OF TRUTH (M-Pesa safe logic)
|--------------------------------------------------------------------------
| A payment is successful IF:
|  - result_code === '0'  (string-safe)
|  - OR MpesaReceiptNumber exists (Mpesa only sends this on success)
*/
$isSuccess =
    (
        isset($txn['result_code']) &&
        (string)$txn['result_code'] === '0'
    )
    ||
    !empty($txn['mpesa_receipt']);

// Derived values
$statusText  = $isSuccess ? 'PAID' : 'FAILED';
$statusClass = $isSuccess ? 'success' : 'failed';

// Safe fallbacks
$entity    = $txn['entity'] ?? '-';
$receiptNo = $txn['receipt_no'] ?? '-';
$mpesaRef = $txn['mpesa_receipt'] ?? '-';
$phone    = formatPhoneDisplay($txn['phone']) ?? '-';
$amount   = number_format((float)($txn['amount'] ?? 0), 2);
$date     = $txn['created_at'] ?? '-';
$result   = $txn['result_desc'] ?? '-';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Payment Receipt</title>
<style>
body {
    font-family: Arial, sans-serif;
    background: #f4f6f8;
    padding: 30px;
}
.receipt {
    max-width: 395px;
    background: #fff;
    margin: auto;
    padding: 25px;
    border-radius: 6px;
    box-shadow: 0 2px 10px rgba(0,0,0,.1);
}
h2 {
    text-align: center;
}
.row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    gap: 10px;
}
.label {
    font-weight: bold;
}
.success { color: #2e7d32; font-weight: bold; }
.failed  { color: red; font-weight: bold; }

.message {
    margin-top: 20px;
    padding: 12px;
    border-radius: 4px;
    text-align: center;
}
.message.success {
    background: #e8f5e9;
    color: #2e7d32;
}
.message.failed {
    background: #ffebee;
    color: red;
}

.actions {
    margin-top: 25px;
    text-align: center;
}
.actions a {
    display: inline-block;
    padding: 10px 18px;
    background: #455a64;
    color: #fff;
    text-decoration: none;
    border-radius: 4px;
    font-weight: bold;
}
</style>
</head>
<body>

<div class="receipt">
    <h2>Payment Receipt</h2>

    <div class="row"><span class="label">Entity:</span><span><?= htmlspecialchars($entity) ?></span></div>
    <div class="row"><span class="label">Receipt No:</span><span><?= formatReceiptNumber($txn['id']) ?></span></div>
    <div class="row"><span class="label">Mpesa Receipt:</span><span><?= htmlspecialchars($mpesaRef) ?></span></div>
    <div class="row"><span class="label">Phone:</span><span><?= htmlspecialchars($phone) ?></span></div>
    <div class="row"><span class="label">Amount:</span><span>KES <?= $amount ?></span></div>
    <div class="row"><span class="label">Status:</span><span class="<?= $statusClass ?>"><?= $statusText ?></span></div>
    <div class="row"><span class="label">Date:</span><span><?= htmlspecialchars($date) ?></span></div>
    <div class="row"><span class="label">Result:</span><span><?= htmlspecialchars($result) ?></span></div>

    <div class="message <?= $statusClass ?>">
        <?= $isSuccess ? 'Payment successful.' : 'Payment not successful.' ?>
    </div>

    <?php if ($isSuccess): ?>
        <div class="actions">
            <a href="receipt_pdf.php?id=<?= urlencode($txn['id']) ?>" target="_blank">
                📄 Download Receipt (PDF)
            </a>
            
        </div>
    <?php endif; ?>
</div>
<a href="/tnd"><img style="margin-left: 50%" SRC="back.png" border=0 height=55 width=79
</body>
</html>
