<?php
require_once __DIR__ . "/../includes/vendor/autoload.php";
require_once __DIR__ . "/../includes/db.php";

use Dompdf\Dompdf;

if (!isset($_GET['reference'])) {
    die("Invalid receipt request.");
}

$reference = trim($_GET['reference']);

// Get the transaction
$stmt = $pdo->prepare("SELECT * FROM transactions WHERE reference = ? LIMIT 1");
$stmt->execute([$reference]);
$txn = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$txn) { die("Transaction not found."); }

$sender_id = $txn['user_id'];

// Fetch Sender
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$sender_id]);
$sender = $stmt->fetch(PDO::FETCH_ASSOC);

// -------------------------------
// Extract data from description
// -------------------------------
$desc = $txn['description'];

$recipient_name = "External Beneficiary";
$recipient_acc  = "Unknown";
$recipient_bank = "Unknown";
$note = "N/A";

// Parse description fields (fallback)
preg_match('/International Transfer to (.*?) \|/i', $desc, $m1);
preg_match('/Acct:\s*(.*?)\s*\|/i', $desc, $m2);
preg_match('/Bank:\s*(.*?)\s*(\||$)/i', $m3);
preg_match('/Note:\s*(.*)$/i', $m4);

if (!empty($m1)) $recipient_name = trim($m1[1]);
if (!empty($m2)) $recipient_acc  = trim($m2[1]);
if (!empty($m3)) $recipient_bank = trim($m3[1]);
if (!empty($m4)) $note = trim($m4[1]);

// ----------------------------------------
// Check if recipient exists in database
// ----------------------------------------
$stmt = $pdo->prepare("SELECT * FROM users WHERE account_number = ? LIMIT 1");
$stmt->execute([$recipient_acc]);
$recipient = $stmt->fetch(PDO::FETCH_ASSOC);

if ($recipient) {
    // Use database details instead
    $recipient_name = $recipient['firstname'] . " " . $recipient['lastname'];
    $recipient_acc  = $recipient['account_number'];

    if (!empty($recipient['bank_name'])) {
        $recipient_bank = $recipient['bank_name'];
    }
}

// -------------------------------
// PDF HTML Design
// -------------------------------
$html = '
<style>
body { font-family: DejaVu Sans, sans-serif; background:#ffffff; }
h2 { text-align:center; margin-bottom:4px; color:#0d6efd; }
small { text-align:center; display:block; margin-bottom:15px; color:#666; }
.section { margin-bottom:12px; }
.label { font-weight:bold; color:#0d6efd; margin-top:10px; }
.value-box { border:1px solid #ddd; padding:8px; border-radius:6px; background:#fafafa; }
.amount { text-align:center; background:#0d6efd; color:#fff; padding:10px; border-radius:8px; font-size:20px; margin:15px 0; }
.footer { text-align:center; font-size:12px; margin-top:25px; color:#444; }
</style>

<h2>BMELLON INTERNATIONAL BANK</h2>
<small>Secure Digital Banking</small>

<div class="amount">'.$sender['currency'].''.number_format($txn['amount'],2).'</div>

<div class="section">
    <div class="label">Sender</div>
    <div class="value-box">
        '.$sender['firstname'].' '.$sender['lastname'].'<br>
        Account: '.$sender['account_number'].'
    </div>
</div>



<div class="section">
    <div class="label">Transaction Info</div>
    <div class="value-box">
        Reference: '.$txn['reference'].'<br>
        Date: '.$txn['created_at'].'<br>
        Status: '.ucfirst($txn['status']).'
    </div>
</div>

<div class="section">
    <div class="label">Description</div>
    <div class="value-box">'.($txn['description'] ?: 'N/A').'</div>
</div>

<div class="footer">
Thank you for banking with BMELLON INTL BANK • © '.date("Y").'
</div>
';

$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper("A4", "portrait");
$dompdf->render();
$dompdf->stream("receipt-$reference.pdf", ["Attachment" => true]);
