<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once("../php/db_connect.php");

$orderId = (int)($_GET['order_id'] ?? 0);

if ($orderId <= 0) {
    die("Invalid order ID.");
}

/*
|--------------------------------------------------------------------------
| GET ORDER DETAILS
|--------------------------------------------------------------------------
*/

$stmt = $conn->prepare("
    SELECT 
        id,
        order_code,
        customer_name,
        customer_email,
        customer_mobile,
        total_price,
        amount_paid,
        remaining_balance,
        payment_status
    FROM orders
    WHERE id = ?
    LIMIT 1
");

if (!$stmt) {
    die("Prepare failed: " . $conn->error);
}

$stmt->bind_param("i", $orderId);
$stmt->execute();
$order = $stmt->get_result()->fetch_assoc();

if (!$order) {
    die("Order not found.");
}

$orderCode = $order['order_code'] ?? ("ORD-" . $orderId);
$totalPrice = (float)($order['total_price'] ?? 0);
$dbAmountPaid = (float)($order['amount_paid'] ?? 0);
$dbRemainingBalance = (float)($order['remaining_balance'] ?? 0);
$dbPaymentStatus = strtolower(trim($order['payment_status'] ?? 'pending'));

/*
|--------------------------------------------------------------------------
| DETERMINE PAYMENT DETAILS
|--------------------------------------------------------------------------
*/


$paymentOption = strtolower(trim($_GET['payment_option'] ?? 'full'));

$amountPaidNow = 0;        // amount sent in this transaction only
$newAmountPaid = 0;        // total paid to save in database
$remainingBalanceNow = 0;  // remaining balance after this payment

if ($paymentOption === 'balance') {

    // This is the amount the user paid now, example: 4500
    $amountPaidNow = (float)($_GET['amount_paid'] ?? 0);

    if ($amountPaidNow <= 0) {
        $amountPaidNow = $dbRemainingBalance;
    }

    // New total paid in database, example: 10500 + 4500 = 15000
    $newAmountPaid = $dbAmountPaid + $amountPaidNow;

    if ($newAmountPaid > $totalPrice) {
        $newAmountPaid = $totalPrice;
    }

    $remainingBalanceNow = $totalPrice - $newAmountPaid;

    if ($remainingBalanceNow < 0) {
        $remainingBalanceNow = 0;
    }

    $paymentStatus = ($remainingBalanceNow > 0) ? "partial" : "paid";
    $paymentLabel = "Balance Payment";

} elseif ($paymentOption === 'partial') {

    $amountPaidNow = (float)($_GET['amount_paid'] ?? 0);

    if ($amountPaidNow <= 0) {
        $amountPaidNow = round($totalPrice * 0.70, 2);
    }

    $newAmountPaid = $amountPaidNow;
    $remainingBalanceNow = $totalPrice - $newAmountPaid;

    if ($remainingBalanceNow < 0) {
        $remainingBalanceNow = 0;
    }

    $paymentStatus = ($remainingBalanceNow > 0) ? "partial" : "paid";
    $paymentLabel = "Partial Payment";

} else {

    $amountPaidNow = $totalPrice;
    $newAmountPaid = $totalPrice;
    $remainingBalanceNow = 0;

    $paymentStatus = "paid";
    $paymentLabel = "Full Payment";
}

/*
|--------------------------------------------------------------------------
| UPDATE ORDER PAYMENT RECORD
|--------------------------------------------------------------------------
*/

$updateStmt = $conn->prepare("
    UPDATE orders
    SET 
        amount_paid = ?,
        remaining_balance = ?,
        payment_status = ?
    WHERE id = ?
");

if (!$updateStmt) {
    die("Update prepare failed: " . $conn->error);
}

$updateStmt->bind_param(
    "ddsi",
    $newAmountPaid,
    $remainingBalanceNow,
    $paymentStatus,
    $orderId
);

$updateStmt->execute();

/*
|--------------------------------------------------------------------------
| RECEIPT DETAILS
|--------------------------------------------------------------------------
*/

$customerName = trim($order['customer_name'] ?? '');

if ($customerName === '') {
    $firstName = $_SESSION['first_name'] ?? 'Customer';
    $lastName = $_SESSION['last_name'] ?? '';
    $customerName = trim($firstName . ' ' . $lastName);
}

$recipient = "TAIPRINT SHOP";
$mobile = "+63 955 866 1346";
$refNo = $_GET['ref'] ?? $orderCode;
$dateTime = date("M d, Y g:i A");

$previousBalance = ($paymentOption === "balance") ? $dbRemainingBalance : $totalPrice;

$receiptMessage = ($paymentStatus === "partial")
    ? "Your partial payment has been recorded successfully in the system."
    : "Your full payment has been recorded successfully in the system.";

$statusLabel = ($paymentStatus === "partial") ? "Partially Paid" : "Fully Paid";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Payment Receipt</title>

<style>
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

body {
    font-family: Arial, sans-serif;
    background: #003cff;
    min-height: 100vh;
}

.receipt-wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 40px 16px;
}

.receipt-card {
    position: relative;
    background: #fff;
    width: 100%;
    max-width: 420px;
    border-radius: 28px 28px 0 0;
    overflow: hidden;
    padding-top: 46px;
}

.success-badge {
    position: absolute;
    top: -28px;
    left: 50%;
    transform: translateX(-50%);
    width: 68px;
    height: 68px;
    border-radius: 50%;
    background: #0d5eff;
    color: #fff;
    font-size: 34px;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 6px solid #fff;
}

.receipt-header {
    text-align: center;
    padding: 24px 24px 18px;
}

.recipient-name {
    font-size: 28px;
    font-weight: 800;
    color: #0d3d9b;
    margin-bottom: 14px;
}

.number-pill {
    display: inline-block;
    background: #eef2ff;
    color: #1745b5;
    padding: 12px 22px;
    border-radius: 999px;
    font-size: 18px;
    font-weight: 700;
    margin-bottom: 10px;
}

.subtext {
    color: #8a8f9d;
    font-size: 16px;
}

.receipt-section {
    margin: 0 24px;
    padding: 24px 0;
    border-top: 1px solid #d9d9d9;
}

.row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    font-size: 18px;
    color: #123c92;
    font-weight: 700;
}

.total-section .row {
    font-size: 20px;
}

.big-amount {
    font-size: 28px;
    font-weight: 800;
}

.receipt-meta {
    background: #f5f7fd;
    padding: 22px 24px;
    display: flex;
    justify-content: space-between;
    gap: 12px;
    flex-wrap: wrap;
    color: #49608f;
    font-size: 15px;
    font-weight: 600;
}

.receipt-details {
    padding: 22px 24px 8px;
    background: #f5f7fd;
}

.detail-row {
    display: flex;
    justify-content: space-between;
    gap: 16px;
    padding: 10px 0;
    font-size: 15px;
    border-bottom: 1px solid #e7ebf5;
}

.detail-row span:first-child {
    color: #6b7280;
}

.detail-row span:last-child {
    color: #163c8c;
    font-weight: 700;
    text-align: right;
}

.success-text {
    color: #1f9d55 !important;
}

.info-card {
    margin: 22px 24px 18px;
    background: #baf0d3;
    border-left: 10px solid #26c48b;
    border-radius: 12px;
    padding: 18px;
    color: #16664a;
}

.info-card h4 {
    margin-bottom: 8px;
    font-size: 22px;
}

.info-card p {
    font-size: 14px;
    line-height: 1.6;
}

.zigzag {
    height: 20px;
    background:
        linear-gradient(-45deg, transparent 10px, #fff 0) 0 10px,
        linear-gradient(45deg, transparent 10px, #fff 0) 0 10px;
    background-size: 20px 20px;
}

.receipt-actions {
    width: 100%;
    max-width: 420px;
    margin-top: 14px;
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.receipt-actions button,
.back-btn {
    width: 100%;
    border: none;
    text-align: center;
    padding: 13px;
    border-radius: 12px;
    font-size: 15px;
    font-weight: 700;
    text-decoration: none;
    cursor: pointer;
}

.download-btn {
    background: #0d5eff;
    color: #fff;
}

.print-btn {
    background: #111827;
    color: #fff;
}

.back-btn {
    background: #edf2ff;
    color: #1745b5;
}

/* PRINT RECEIPT STYLE */
@media print {
    @page {
        size: 80mm auto;
        margin: 0;
    }

    body {
        background: #fff;
        margin: 0;
        padding: 0;
    }

    body * {
        visibility: hidden;
    }

    .receipt-card,
    .receipt-card * {
        visibility: visible;
    }

    .receipt-wrapper {
        display: block;
        padding: 0;
    }

    .receipt-card {
        position: absolute;
        left: 0;
        top: 0;
        width: 80mm;
        max-width: 80mm;
        box-shadow: none;
        border-radius: 0;
        padding: 10px;
        overflow: visible;
        font-family: "Courier New", monospace;
        font-size: 12px;
        color: #000;
    }

    .success-badge,
    .zigzag {
        display: none;
    }

    .receipt-header {
        padding: 0;
        text-align: center;
    }

    .recipient-name {
        font-size: 16px;
        color: #000;
        margin-bottom: 4px;
        letter-spacing: 1px;
    }

    .number-pill {
        background: transparent;
        color: #000;
        padding: 0;
        font-size: 12px;
        font-weight: normal;
        margin-bottom: 2px;
    }

    .subtext {
        color: #000;
        font-size: 12px;
    }

    .receipt-section {
        margin: 8px 0 0;
        padding: 8px 0;
        border-top: 1px dashed #000;
    }

    .row {
        color: #000;
        font-size: 12px;
        font-weight: normal;
    }

    .row span:last-child {
        font-weight: bold;
    }

    .total-section .row {
        font-size: 13px;
        font-weight: bold;
    }

    .big-amount {
        font-size: 13px;
        font-weight: bold;
    }

    .receipt-meta {
        background: #fff;
        padding: 8px 0;
        border-top: 1px dashed #000;
        border-bottom: 1px dashed #000;
        color: #000;
        font-size: 11px;
        display: flex;
        justify-content: space-between;
    }

    .receipt-details {
        background: #fff;
        padding: 8px 0;
    }

    .detail-row {
        font-size: 12px;
        border-bottom: none;
        padding: 4px 0;
    }

    .detail-row span:first-child,
    .detail-row span:last-child,
    .success-text {
        color: #000 !important;
    }

    .info-card {
        margin: 8px 0 0;
        padding: 8px 0;
        background: #fff;
        border: none;
        border-top: 1px dashed #000;
        color: #000;
        text-align: center;
        border-radius: 0;
    }

    .info-card h4 {
        font-size: 12px;
        margin-bottom: 4px;
        font-weight: bold;
    }

    .info-card p {
        font-size: 11px;
        line-height: 1.4;
    }

    .receipt-actions {
        display: none;
    }
}
</style>
</head>

<body>

<div class="receipt-wrapper">

    <div class="receipt-card" id="receiptCard">
        <div class="success-badge">✓</div>

        <div class="receipt-header">
            <h2 class="recipient-name"><?= htmlspecialchars($recipient) ?></h2>
            <div class="number-pill"><?= htmlspecialchars($mobile) ?></div>
            <p class="subtext">Sent via Digital Wallet</p>
        </div>

        <div class="receipt-section">
            <div class="row">
                <span>Amount</span>
                <span>₱<?= number_format($amountPaidNow, 2) ?></span>
            </div>
        </div>

        <div class="receipt-section total-section">
            <div class="row">
                <span>Total Amount Sent</span>
                <span class="big-amount">₱<?= number_format($amountPaidNow, 2) ?></span>
            </div>
        </div>

        <div class="receipt-meta">
            <span><strong>Ref No.</strong> <?= htmlspecialchars($refNo) ?></span>
            <span><?= htmlspecialchars($dateTime) ?></span>
        </div>

        <div class="receipt-details">
            <div class="detail-row">
                <span>Customer</span>
                <span><?= htmlspecialchars($customerName) ?></span>
            </div>

            <div class="detail-row">
                <span>Payment Type</span>
                <span><?= htmlspecialchars($paymentLabel) ?></span>
            </div>

            <div class="detail-row">
                <span>Previous Balance</span>
                <span>₱<?= number_format($previousBalance, 2) ?></span>
            </div>

            <div class="detail-row">
                <span>Amount Paid</span>
                <span>₱<?= number_format($amountPaidNow, 2) ?></span>
            </div>

            <div class="detail-row">
                <span>Remaining Balance</span>
                <span>₱<?= number_format($remainingBalanceNow, 2) ?></span>
            </div>

            <div class="detail-row">
                <span>Status</span>
                <span class="success-text"><?= htmlspecialchars($statusLabel) ?></span>
            </div>
        </div>

        <div class="info-card">
            <h4>Payment Recorded</h4>
            <p><?= htmlspecialchars($receiptMessage) ?></p>
        </div>

        <div class="zigzag"></div>
    </div>

    <div class="receipt-actions">
        <button type="button" class="download-btn" onclick="downloadReceipt()">Download Receipt</button>
        <button type="button" class="print-btn" onclick="window.print()">Print Receipt</button>
        <a href="customer.php?page=track-order" class="back-btn">Back to Orders</a>
    </div>

</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>

<script>
function downloadReceipt() {
    const receipt = document.getElementById("receiptCard");

    const options = {
        margin: 0,
        filename: "TAIPRINT-Receipt-Order-<?= (int)$orderId ?>.pdf",
        image: {
            type: "jpeg",
            quality: 0.98
        },
        html2canvas: {
            scale: 2,
            backgroundColor: "#ffffff"
        },
        jsPDF: {
            unit: "mm",
            format: [100, 190],
            orientation: "portrait"
        }
    };

    html2pdf().set(options).from(receipt).save();
}
</script>

</body>
</html>