<?php
require 'config.php';
require 'fpdf/fpdf.php';
require __DIR__ . '/phpqrcode/qrlib.php';

/* =========================
   HELPER FUNCTIONS
========================= */
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;
}

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

/* =========================
   COMPANY DETAILS
========================= */
define('COMPANY_NAME', 'Transaction Receipt');
define('COMPANY_PHONE', '+254 720 050708');
define('COMPANY_EMAIL', 'info@swingtide.com');
define('COMPANY_LOGO', 'logo.png');

$SUCCESS_STATUSES = ['SUCCESS', 'paid', 'COMPLETED'];

/* =========================
   FETCH LATEST TRANSACTION
========================= */
$stmt = $pdo->query("SELECT * FROM mpesa_payments ORDER BY id DESC LIMIT 1");
$txn = $stmt->fetch(PDO::FETCH_ASSOC);



/* =========================
   PDF GENERATION (PRINT PDF)
========================= */

if (isset($_GET['pdf']) && $txn && in_array($txn['status'], $SUCCESS_STATUSES)) {

    $pdf = new FPDF('P', 'mm', 'A4');
    $pdf->AddPage();

    if (file_exists(COMPANY_LOGO)) {
        $pdf->Image(COMPANY_LOGO, 80, 10, 40);
        $pdf->Ln(30);
    }

    $pdf->SetFont('Arial', 'B', 16);
    $pdf->Cell(0, 10, 'PAYMENT RECEIPT', 0, 1, 'C');
    $pdf->Ln(5);

    $pdf->SetFont('Arial', '', 12);
    $pdf->Cell(0, 8, 'Entity: ' . $txn['entity'], 0, 1);
    $pdf->Cell(0, 8, 'Receipt No: ' . formatReceiptNumber($txn['id']), 0, 1);
    $pdf->Cell(0, 8, 'Mpesa Receipt: ' . $txn['mpesa_receipt'], 0, 1);
    $pdf->Cell(0, 8, 'Phone: ' . formatPhoneDisplay($txn['phone']), 0, 1);
    $pdf->Cell(0, 8, 'Amount: KES ' . number_format($txn['amount'], 2), 0, 1);
    $pdf->Cell(0, 8, 'Status: ' . strtoupper($txn['status']), 0, 1);
    $pdf->Cell(0, 8, 'Date: ' . $txn['created_at'], 0, 1);
    $pdf->Cell(0, 8, 'Result Desc: ' . $txn['result_desc'], 0, 1);

    $pdf->Ln(10);
    $pdf->SetFont('Arial', 'I', 10);
    $pdf->Cell(0, 6, COMPANY_NAME, 0, 1, 'C');
    $pdf->Cell(0, 6, COMPANY_PHONE . ' | ' . COMPANY_EMAIL, 0, 1, 'C');

    // OPEN PDF IN BROWSER (for printing)
    $pdf->Output('I', formatReceiptNumber($txn['id']) . '.pdf');
    exit;
    
 
}
?>



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Transaction Receipt</title>

    <!-- MOBILE RESPONSIVE -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <style>
        body {
            margin: 0;
            padding: 0;
            background: #f2f2f2;
            font-family: Arial, sans-serif;
        }

        .receipt {
            max-width: 380px;
            margin: 20px auto;
            background: #fff;
            padding: 20px;
            border: 1px solid #ccc;
            box-sizing: border-box;
        }

        img {
            display: block;
            margin: 0 auto 10px;
            max-width: 120px;
        }

        h2 {
            text-align: center;
            margin: 5px 0;
        }

        hr {
            border: 1px dashed #000;
            margin: 10px 0;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
        }

        td {
            padding: 6px 0;
        }

        .success {
            color: green;
            font-weight: bold;
        }

        .failed {
            color: red;
            font-weight: bold;
        }

        button {
            width: 100%;
            padding: 12px;
            margin-top: 10px;
            font-size: 16px;
            cursor: pointer;
        }

        @media (max-width: 600px) {
            .receipt {
                margin: 10px;
                padding: 15px;
            }

            table tr {
                display: block;
                margin-bottom: 8px;
            }

            table td {
                display: flex;
                justify-content: space-between;
            }

            table td:first-child {
                font-weight: bold;
            }
        }
    </style>
</head>
<body>
    

<div class="receipt">

<?php if (!$txn): ?>

    <p>No transactions found.</p>

<?php else: ?>

    <?php if (file_exists(COMPANY_LOGO)): ?>
        <img src="<?= COMPANY_LOGO ?>" alt="Logo">
    <?php endif; ?>

    <h2><?= COMPANY_NAME ?></h2>
    <hr>

    <table>
        <tr>
            <tr>
            <td>Entity</td>
            <td><?= htmlspecialchars($txn['entity']) ?></td>
        </tr>
        <tr>
            <td>Receipt No</td>
            <td><?= formatReceiptNumber($txn['id']) ?></td>
        </tr>
        <tr>
            <td>Mpesa Receipt</td>
            <td><?= htmlspecialchars($txn['mpesa_receipt']) ?></td>
        </tr>
        <tr>
            <td>Phone</td>
            <td><?= formatPhoneDisplay($txn['phone']) ?></td>
        </tr>
        <tr>
            <td>Amount</td>
            <td>KES <?= number_format($txn['amount'], 2) ?></td>
        </tr>
        <tr>
            <td>Status</td>
            <td class="<?= in_array($txn['status'], $SUCCESS_STATUSES) ? 'success' : 'failed' ?>">
                <?= strtoupper($txn['status']) ?>
            </td>
        </tr>
        <tr>
            <td>Date</td>
            <td><?= htmlspecialchars($txn['created_at']) ?></td>
        </tr>
        <tr>
            <td>Result Desc</td>
            <td><?= htmlspecialchars($txn['result_desc']) ?></td>
        </tr>
        <tr>
    </table>

    <hr>
    <p style="text-align:center;">
        <?= in_array($txn['status'], $SUCCESS_STATUSES)
            ? 'Thank you for your payment.'
            : 'Payment was not successful.'
        ?>
    </p>

    <?php if (in_array($txn['status'], $SUCCESS_STATUSES)): ?>
        <a href="?pdf=1" target="_blank">
            <button>Print PDF Receipt</button>
        </a>
        
        
    <?php endif; ?>

<?php endif; ?>

</div>

</body>
</html>
