<?php
session_start();

require_once __DIR__ . '/vendor/autoload.php';

use App\Core\Database;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Writer\PngWriter;

require_once __DIR__ . '/lib/PayNowQR.php';

$db = Database::connect();

/*
|--------------------------------------------------------------------------
| Validate Booking
|--------------------------------------------------------------------------
*/

$ref = $_GET['ref'] ?? null;

if (!$ref) {
    die('Invalid booking reference.');
}

$stmt = $db->prepare("
    SELECT *
    FROM bookings
    WHERE booking_reference = ?
    AND status = 'accepted'
    LIMIT 1
");
$stmt->execute([$ref]);
$booking = $stmt->fetch();

if (!$booking) {
    die('Booking not eligible for PayNow payment.');
}

/*
|--------------------------------------------------------------------------
| Check Existing Payment
|--------------------------------------------------------------------------
*/

$stmt = $db->prepare("
    SELECT *
    FROM payments
    WHERE booking_id = ?
    AND payment_status = 'paid'
    LIMIT 1
");
$stmt->execute([$booking['id']]);
$existingPayment = $stmt->fetch();

if ($existingPayment) {
    die('This booking has already been paid.');
}

/*
|--------------------------------------------------------------------------
| Generate PayNow QR Payload
|--------------------------------------------------------------------------
*/

$uen = "202512345Z"; // Replace with real UEN
$amount = $booking['final_price'];
$reference = $booking['booking_reference'];

$qrPayload = PayNowQR::generate($uen, $amount, $reference);

/*
|--------------------------------------------------------------------------
| Generate QR Image (v5 Builder API)
|--------------------------------------------------------------------------
*/

$result = Builder::create()
    ->writer(new PngWriter())
    ->data($qrPayload)
    ->size(320)
    ->margin(10)
    ->build();

/*
|--------------------------------------------------------------------------
| Save QR File
|--------------------------------------------------------------------------
*/

$qrDirectory = __DIR__ . '/assets/tmp/';

if (!is_dir($qrDirectory)) {
    mkdir($qrDirectory, 0755, true);
}

$qrFileName = 'paynow_' . $booking['id'] . '_' . time() . '.png';
$qrFilePath = $qrDirectory . $qrFileName;

file_put_contents($qrFilePath, $result->getString());

$qrFilePublic = 'assets/tmp/' . $qrFileName;

?>

<?php require_once __DIR__ . '/includes/book_header.php'; ?>

<section class="section-padding">
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-6">

<div class="booking-card p-5 text-center">

<h4 class="gold-text mb-4">PayNow QR Payment</h4>

<p class="mb-3">
Scan the QR code below using your banking app.
</p>

<img src="<?php echo $qrFilePublic; ?>"
class="img-fluid mb-4"
style="max-width:280px;">

<p>
<strong>Amount:</strong>
<span class="gold-text">
$<?php echo number_format($amount, 2); ?>
</span>
</p>

<p>
<strong>Reference:</strong>
<?php echo htmlspecialchars($reference); ?>
</p>

<hr>

<p class="mb-3">
After completing the transfer, enter your PayNow transaction reference:
</p>

<form method="POST" action="process_payment_manual.php">

<input type="hidden"
name="ref"
value="<?php echo htmlspecialchars($reference); ?>">

<div class="form-group">
<input type="text"
name="transaction_reference"
class="form-control"
placeholder="Enter PayNow Transaction Reference"
required>
</div>

<button type="submit"
class="btn btn-gold btn-block mt-3">
Confirm Payment
</button>

</form>

</div>

</div>
</div>
</div>
</section>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
