<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

require __DIR__ . '/config.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;
}

if (!isset($pdo)) {
    die('Database connection not found.');
}

/* 🔐 Secret key (KEEP PRIVATE) */
define('RECEIPT_SECRET', 'CHANGE_THIS_TO_A_RANDOM_SECRET');

/* Safe output */
function e($v) {
    return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
}

/* Get receipt number */
$id = $_GET['r'] ?? '';
if ($id === '') {
    die('Invalid verification request.');
}

/* Fetch transaction */
$stmt = $pdo->prepare("
    SELECT entity, id, mpesa_receipt, phone, amount, status, created_at
    FROM mpesa_payments
    WHERE id = ?
    LIMIT 1
");
$stmt->execute([$id]);
$txn = $stmt->fetch(PDO::FETCH_ASSOC);

/* Default flags */
$result = 'INVALID';
$fraudFlags = [];

/* Fraud & validity checks */
if (!$txn) {
    $fraudFlags[] = 'Receipt does not exist';
} else {
    $status = strtoupper(trim($txn['status']));

    /* 🔐 Hash verification */
    $expectedHash = hash(
        'sha256',
        $txn['id'] .
        $txn['mpesa_receipt'] .
        $txn['amount'] .
        RECEIPT_SECRET
    );

    $providedHash = hash(
        'sha256',
        $txn['id'] .
        $txn['mpesa_receipt'] .
        $txn['amount'] .
        RECEIPT_SECRET
    );

    if ($expectedHash !== $providedHash) {
        $fraudFlags[] = 'Receipt data integrity compromised';
    }

    if ($status !== 'PAID') {
        $fraudFlags[] = 'Payment not completed';
    }

    if ($txn['amount'] <= 0) {
        $fraudFlags[] = 'Invalid amount detected';
    }

    if (empty($fraudFlags)) {
        $result = 'VALID';
    } else {
        $result = 'FLAGGED';
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Receipt Verification</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        body {
            font-family: Arial, sans-serif;
            background: #f4f4f4;
            padding: 15px;
        }
        .paid {
            color: #0a7a3b;
            font-weight: bold;
        }
        .card {
            max-width: 420px;
            margin: auto;
            background: #fff;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 10px rgba(0,0,0,.12);
        }
        h2 {
            text-align: center;
            margin-bottom: 10px;
        }
        .badge {
            padding: 10px;
            border-radius: 6px;
            text-align: center;
            font-weight: bold;
            margin-bottom: 15px;
        }
        .valid {
            background: #e6f9ee;
            color: #0a7a3b;
        }
        .flagged {
            background: #fff3cd;
            color: #856404;
        }
        .invalid {
            background: #fdecea;
            color: #b71c1c;
        }
        .row {
            margin: 6px 0;
            font-size: 14px;
        }
        .label {
            font-weight: bold;
        }
       
        .btn {
            display: block;
            margin-top: 15px;
            padding: 10px;
            text-align: center;
            background: #007bff;
            color: #fff;
            text-decoration: none;
            border-radius: 6px;
        }
    </style>
</head>
<body>

<div class="card">
    <h2>Receipt Verification</h2>

    <?php if ($result === 'VALID'): ?>
        <div class="badge valid">✔ VERIFIED & AUTHENTIC</div>
        

        <div class="row"><span class="label">Entity:</span> <?= e($txn['entity']) ?></div>
        <div class="row"><span class="label">Receipt No:</span> <?= formatReceiptNumber($txn['id']) ?></div>
        <div class="row"><span class="label">Mpesa Receipt:</span> <?= e($txn['mpesa_receipt']) ?></div>
        <div class="row"><span class="label">Phone:</span> <?= formatPhoneDisplay($txn['phone']) ?></div>
        <div class="row"><span class="label">Amount:</span> KES <?= number_format((float)$txn['amount'], 2) ?></div>
        <div class="row"><span class="label">Status:</span><span class="paid">PAID</span></div>
        <div class="row"><span class="label">Date:</span> <?= e($txn['created_at']) ?></div>

        🧾 <a class="btn" href="receipt_pdf.php?id=<?= urlencode($txn['id']) ?>" target="_blank">Download PDF Receipt</a>

    <?php elseif ($result === 'FLAGGED'): ?>
        <div class="badge flagged">⚠ RECEIPT FLAGGED</div>

        <?php foreach ($fraudFlags as $flag): ?>
            <div class="row">• <?= e($flag) ?></div>
        <?php endforeach; ?>

    <?php else: ?>
        <div class="badge invalid">✖ INVALID OR FAKE RECEIPT</div>
    <?php endif; ?>
</div>

</body>
</html>
