<?php require_once __DIR__ . '/../admin/auth.php'; ?>


<?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;
}

/*
|--------------------------------------------------------------------------
| HANDLE SEARCH
|-------------------------------------------------------------------------- 
*/
$search = trim($_GET['search'] ?? '');

try {
    if ($search !== '') {
        // Search by receipt, mpesa code, or phone
        $stmt = $pdo->prepare("
            SELECT *
            FROM mpesa_payments
            WHERE
                deleted_at IS NULL
                AND (
                    mpesa_receipt = :search
                    OR phone = :search
                    OR id = :search
                )
            ORDER BY created_at DESC
            LIMIT 1
        ");
        $stmt->execute(['search' => $search]);
    } else {
        // Default: latest transaction
        $stmt = $pdo->query("
            SELECT *
            FROM mpesa_payments
            WHERE deleted_at IS NULL
            ORDER BY created_at DESC
            LIMIT 1
        ");
    }

    $txn = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    die("Error loading receipt.");
}

$notFound = !$txn;

/*
|--------------------------------------------------------------------------
| M-PESA SAFE SUCCESS LOGIC
|-------------------------------------------------------------------------- 
*/
$isSuccess = !$notFound && (
    (
        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    = $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: 520px;
    background: #fff;
    margin: auto;
    padding: 25px;
    border-radius: 6px;
    box-shadow: 0 2px 10px rgba(0,0,0,.1);
}
h2 {
    text-align: center;
}
.search-box {
    display: flex;
    gap: 8px;
    margin-bottom: 20px;
}
.search-box input {
    flex: 1;
    padding: 8px;
}
.search-box button {
    padding: 8px 14px;
    font-weight: bold;
    cursor: pointer;
}
.row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    gap: 10px;
}
.label {
    font-weight: bold;
}
.success { color: #2e7d32; font-weight: bold; }
.failed  { color: #c62828; 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: #c62828;
}

.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;
}
.not-found {
    text-align: center;
    color: #c62828;
    font-weight: bold;
}
</style>
</head>
<body>
    
    <a href="/admin/logout.php?from=<?= urlencode($_SERVER['REQUEST_URI']) ?>"
   style="float:right;color:#dc2626;text-decoration:none;">
   Logout
</a>

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

    <!-- SEARCH FORM -->
    <form class="search-box" method="get">
        <input
            type="text"
            name="search"
            placeholder="Search by Mpesa Code / Phone / Receipt No"
            value="<?= htmlspecialchars($search) ?>"
        >
        <button type="submit">Search</button>
    </form>

    <?php if ($notFound): ?>
        <div class="not-found">No transaction found.</div>
    <?php else: ?>

        <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><?= formatPhoneDisplay($txn['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>

        
        <div class="actions">
            <a href="receipt_pdf.php?id=<?= urlencode($txn['id']) ?>">
                📄 Download Receipt (PDF)
            </a>
            <a href="search.php" target="_blank">Bulk Search(Receipt)</a>
        </div>
    <?php endif; ?>

</div>
<div style="text-align: center;">
    <a href="/pay"><img src="back.png" border=0 height=55 width=79></a>
</div>
</body>
</html>
