<?php
// ----- PDO Connection -----
$host = 'localhost';
$dbname = 'demoptma_publications';
$username = 'demoptma_publications';
$password = 'dj$JN)hJerjG';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// ----- Get Invoice -----
$invoiceId = $_GET['reg'] ?? null;
if (!$invoiceId) {
    die("Invoice not found");
}

$stmt = $pdo->prepare("SELECT * FROM invoices WHERE id = ?");
$stmt->execute([$invoiceId]);
$invoice = $stmt->fetch();

if (!$invoice) {
    die("Invoice not found");
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="assets/img/favicon.png" type="image/x-icon">
    <title>Invoice #<?= htmlspecialchars($invoice['id']) ?> | WOS Publications UK</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9ff;
            font-family: 'Poppins', sans-serif;
            color: #1c1e21;
        }

        .invoice-card {
            background: #fff;
            border-radius: 20px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
            padding: 40px;
            max-width: 900px;
            margin: 50px auto;
        }

        .invoice-header h1 {
            font-weight: 700;
            color: #043773;
        }

        .amount-box {
            background-color: #043773;
            color: #fff;
            border-radius: 12px;
            padding: 15px 20px;
            text-align: right;
            font-size: 1.5rem;
            font-weight: 600;
        }

        .info-label {
            font-weight: 600;
            color: #6c757d;
            margin-bottom: 2rem;
            font-size: 1.2rem;
            text-decoration: underline;
        }

        .desc-row {
            background: #f1f4ff;
            border-radius: 10px;
            padding: 10px 15px;
            margin-bottom: 10px;
        }

        .desc-row span {
            display: inline-block;
            min-width: 150px;
        }

        .note {
            font-size: 0.9rem;
            color: #6c757d;
            margin-top: 30px;
        }

        .pay-btn {
            background-color: #043773;
            color: white;
            border: none;
            border-radius: 50px;
            padding: 12px 40px;
            font-size: 1.1rem;
            transition: 0.3s;
        }

        .pay-btn:hover {
            background-color: #0033cc;
        }

        p {
            line-height: 7px;
        }
        
        .invoice-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 14px;
}

.invoice-table thead th {
    background: #043773;
    color: #fff;
    padding: 12px;
    font-weight: 600;
}

.invoice-table tbody td {
    padding: 14px 12px;
    background: #f3f4f6;
    vertical-align: top;
}

/* alignment helpers */
.text-end { text-align: right; }
.text-center { text-align: center; }
.text-start { text-align: left; }

/* optional nice rounded header */
.invoice-table thead th:first-child {
    border-top-left-radius: 8px;
}
.invoice-table thead th:last-child {
    border-top-right-radius: 8px;
}
    </style>
</head>

<body>

    <div class="invoice-card">
        <div class="d-flex justify-content-between align-items-center mb-4 invoice-header">
            <img src="assets/img/logo-new.png" width="20%">
            <!--<h1>Invoice #<?= htmlspecialchars($invoice['id']) ?></h1>-->
            <div class="amount-box">
                Total: $<?= number_format($invoice['amount'], 2) ?>
            </div>
        </div>
        <hr style="padding-bottom:2rem;">
        <div class="row mb-4">
            <div class="col-md-6">
                <p class="info-label">Client</p>
                <p><?= htmlspecialchars($invoice['client_name']) ?></p>
                <p><?= htmlspecialchars($invoice['client_email'] ?? 'N/A') ?></p>
                <p><?= htmlspecialchars($invoice['client_phone'] ?? '') ?></p>
            </div>
            <div class="col-md-6" style="text-align:end;">
                <p class="info-label">Company</p>
                <p>WOS Publications UK</p>
                <p>info@solvingpublishing.com</p>
                <p>(321) 265-7614</p>
            </div>
        </div>
        <hr style="padding-bottom:2rem;">
        <h5 class="fw-bold mb-3">Invoice Details</h5>
        <!--<div class="desc-row d-flex justify-content-between" style="color:white; background-color:#043773;">-->
        <!--    <span>Description</span>-->
        <!--    <span>Rate</span>-->
        <!--    <span>Qty</span>-->
        <!--    <span>Line Total</span>-->
        <!--</div>-->

        <!--<div class="desc-row d-flex justify-content-between align-items-center">-->
        <!--    <span><?= htmlspecialchars($invoice['package']) ?></span>-->
        <!--    <span>$<?= number_format($invoice['amount'], 2) ?></span>-->
        <!--    <span>1</span>-->
        <!--    <span>$<?= number_format($invoice['amount'], 2) ?></span>-->
        <!--</div>-->
        
        <table class="invoice-table">
            <thead>
                <tr>
                    <th class="text-start">Description</th>
                    <th class="text-end">Rate</th>
                    <th class="text-center">Qty</th>
                    <th class="text-end">Line Total</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><?= nl2br(htmlspecialchars($invoice['package'])) ?></td>
                    <td class="text-end">$<?= number_format($invoice['amount'], 2) ?></td>
                    <td class="text-center">1</td>
                    <td class="text-end">$<?= number_format($invoice['amount'], 2) ?></td>
                </tr>
            </tbody>
        </table>

        <?php if (strtolower($invoice['payment_status']) === 'paid'): ?>
            <div class="text-center" style="padding-top: 2rem;">
                <h3 class="text-success fw-bold">✅ Payment Successful</h3>
                <p>Thank you! This invoice has been paid successfully.</p>
            </div>
        
        <?php else: ?>
            <hr class="my-4">
            
            <?php if (strtolower($invoice['merchant']) === 'stripe'): ?>


                <!-- ===================== -->
                <!-- STRIPE PAYMENT FORM -->
                <!-- ===================== -->




                <form id="stripePaymentForm" method="post" novalidate>
                    <input type="hidden" name="invoice_id" value="<?= $invoice['id'] ?>">
                    <input type="hidden" name="merchant" value="Stripe">
                    <input type="hidden" id="payment_method_id" name="payment_method_id">


                    <div class="mb-3">
                        <label class="form-label">Name on Card</label>
                        <input type="text" id="cardName" class="form-control" required>
                    </div>


                    <div class="mb-3">
                        <label class="form-label">Billing Address</label>
                        <input type="text" id="cardAddress" class="form-control" required>
                    </div>


                    <div class="mb-3">
                        <label class="form-label">Card Details</label>
                        <div id="card-element" class="form-control" style="padding:10px;"></div>
                    </div>


                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Zip</label>
                            <input type="text" id="zip" class="form-control">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">State</label>
                            <input type="text" id="state" class="form-control">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">City</label>
                            <input type="text" id="city" class="form-control">
                        </div>
                    </div>


                    <div id="cardErrors" class="text-danger mb-2"></div>


                    <div class="text-center">
                        <button type="submit" class="pay-btn">Pay Now</button>
                    </div>
                </form>


                <script src="https://js.stripe.com/v3/"></script>
                <script>
                    const stripe = Stripe("pk_live_51Q1AUQAwacMkjoVrYWRtnQYR1lYvSH1vOA43ToJefQPmQFPhKmzcpHxJadskVPP8oFPkrqR0yXKLiGk4zde7nYFC00jIkbG1KA");
                    const elements = stripe.elements();


                    const card = elements.create("card", {
                        hidePostalCode: true
                    });
                    card.mount("#card-element");


                    document
                        .getElementById("stripePaymentForm")
                        .addEventListener("submit", async function(e) {
                            e.preventDefault();


                            const {
                                paymentMethod,
                                error
                            } = await stripe.createPaymentMethod({
                                type: "card",
                                card: card,
                                billing_details: {
                                    name: document.getElementById("cardName").value,
                                    address: {
                                        line1: document.getElementById("cardAddress").value,
                                        city: document.getElementById("city").value,
                                        state: document.getElementById("state").value,
                                        postal_code: document.getElementById("zip").value,
                                    },
                                },
                            });


                            if (error) {
                                document.getElementById("cardErrors").innerText = error.message;
                                return;
                            }


                            document.getElementById("payment_method_id").value = paymentMethod.id;
                            this.action = "process_payment.php";
                            this.submit();
                        });
                </script>

            <?php elseif (strtolower($invoice['merchant']) === 'klarna'): ?>

                <!-- ===================== -->
                <!-- KLARNA → STRIPE CHECKOUT REDIRECT -->
                <!-- ===================== -->
            
                <div class="text-center my-4">
                    <p class="mb-3 fw-bold">Pay securely using Klarna Installments</p>
            
                    <form method="post" action="create_stripe_checkout.php">
                        <input type="hidden" name="invoice_id" value="<?= $invoice['id'] ?>">
                        <input type="hidden" name="amount" value="<?= $invoice['amount'] ?>">
                        <input type="hidden" name="client_email" value="<?= htmlspecialchars($invoice['client_email']) ?>">
                        <input type="hidden" name="client_name" value="<?= htmlspecialchars($invoice['client_name']) ?>">
                        <input type="hidden" name="payment_method" value="klarna">
            
                        <button type="submit" class="pay-btn">
                            Pay with Klarna
                        </button>
                    </form>
                </div>
            <?php else: ?>
                <form id="paymentForm" action="process_payment.php" method="post" novalidate>
                    <input type="hidden" name="invoice_id" value="<?= $invoice['id'] ?>">
                    <input type="hidden" name="merchant" value="<?= $invoice['merchant'] ?>">
                    <input type="hidden" name="amount" value="<?= $invoice['amount'] ?>">
                    <input type="hidden" name="client_name" value="<?= htmlspecialchars($invoice['client_name']) ?>">
                    <input type="hidden" name="client_email" value="<?= htmlspecialchars($invoice['client_email'] ?? 'N/A') ?>">
                    <input type="hidden" name="client_phone" value="<?= htmlspecialchars($invoice['client_phone'] ?? '') ?>">



                    <!-- ALL OTHER FIELDS -->
                    <div id="cardDetailsSection">

                        <div class="mb-3">
                            <label class="form-label">Name on Card</label>
                            <input type="text" id="cardName" name="card_name" class="form-control" inputmode="text"
                                placeholder="e.g. John Doe" required>
                            <!-- <div id="cardNumberHelp" class="help-text">Invalid card number.</div> -->
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Card Holder Address</label>
                            <input type="text" id="cardAddress" name="card_address" class="form-control" inputmode="text"
                                placeholder="e.g. 123 Main Street or Street address" required>
                            <!-- <div id="cardNumberHelp" class="help-text">Invalid card number.</div> -->
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Card Number</label>
                            <input type="text" id="cardNumber" name="card_num" class="form-control" inputmode="numeric"
                                autocomplete="cc-number" placeholder="---- ---- ---- ----" required>
                            <!-- <div id="cardNumberHelp" class="help-text">Invalid card number.</div> -->
                        </div>

                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Expiry (MM/YY)</label>
                                <input type="text" id="expiry" name="exp" class="form-control" placeholder="MM/YY" required>
                                <!-- <div id="expiryHelp" class="help-text">Invalid expiry format.</div> -->
                            </div>

                            <div class="col-md-4 mb-3">
                                <label class="form-label">CVV</label>
                                <input type="text" id="cvv" name="cvv" class="form-control" inputmode="numeric" autocomplete="cc-csc"
                                    required>
                                <!-- <div id="cvvHelp" class="help-text">Invalid CVV.</div> -->
                            </div>

                            <div class="col-md-4 mb-3">
                                <label class="form-label">Zip Code</label>
                                <input type="text" id="zip" name="zip" class="form-control" inputmode="numeric" maxlength="5"
                                    placeholder="e.g. 90210" required>
                                <!-- <div id="zipHelp" class="help-text">Zip must be 5 digits.</div> -->
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">State</label>
                                <!--<select id="stateSelect" name="state" class="form-select" required>-->
                                <!--  <option value="">Select state</option>-->
                                <!--</select>-->
                                <input class="form-control" type="text" name="state" id="state" placeholder="State">
                            </div>

                            <div class="col-md-6 mb-3">
                                <label class="form-label">City</label>
                                <!--<select id="citySelect" name="city" class="form-select" required>-->
                                <!--  <option value="">Select city</option>-->
                                <!--</select>-->
                                <input class="form-control" type="text" name="city" id="city" placeholder="City">
                            </div>
                        </div>

                        <div class="text-center">
                            <button type="submit" class="pay-btn">Pay Now</button>
                        </div>

                    </div>
                </form>
            <?php endif; ?>
        <?php endif; ?>
    </div>
    <script>
        /* -------------------------
       DOM references (must be first)
       ------------------------- */
        const cardTypeSelect = document.getElementById('cardType');
        const cardNumberInput = document.getElementById('cardNumber');
        const cvvInput = document.getElementById('cvv');
        const expiryInput = document.getElementById('expiry');
        const zipInput = document.getElementById('zip');
        const stateSelect = document.getElementById('stateSelect');
        const citySelect = document.getElementById('citySelect');
        const form = document.getElementById('paymentForm');
        const cardDetailsSection = document.getElementById('cardDetailsSection');

        /* -------------------------
           Card rules and state/city maps (keep your existing maps)
           ------------------------- */
        const cardRules = {
            visa: {
                maxDigits: 16,
                groups: [4, 4, 4, 4]
            },
            mastercard: {
                maxDigits: 16,
                groups: [4, 4, 4, 4]
            },
            discover: {
                maxDigits: 16,
                groups: [4, 4, 4, 4]
            },
            amex: {
                maxDigits: 15,
                groups: [4, 6, 5]
            },
            diners: {
                maxDigits: 14,
                groups: [4, 6, 4]
            },
            unionpay: {
                maxDigits: 19,
                groups: [4, 4, 4, 4, 3]
            }
        };

        /* -------------------------
           Helpers
           ------------------------- */
        function onlyDigits(value) {
            return value.replace(/\D/g, '');
        }

        function formatWithGroups(digits, groups) {
            let parts = [],
                i = 0;
            for (const g of groups) {
                if (i >= digits.length) break;
                parts.push(digits.substr(i, g));
                i += g;
            }
            if (i < digits.length) parts.push(digits.substr(i));
            return parts.join('-');
        }

        function setError(el, message, show) {
            const help = document.getElementById(el.id + "Help");
            if (show) {
                el.classList.add('invalid');
                if (help) {
                    help.textContent = message;
                    help.classList.add('show');
                }
            } else {
                el.classList.remove('invalid');
                if (help) {
                    help.classList.remove('show');
                }
            }
        }

        /* -------------------------
           Apply card type settings (safe: only runs when a valid type exists)
           ------------------------- */


        /* -------------------------
           Reformat card number according to selected type (safe fallback to visa)
           ------------------------- */




        // CVV numeric

        // Zip numeric
        zipInput.addEventListener('input', () => {
            zipInput.value = onlyDigits(zipInput.value).slice(0, 5);
            setError(zipInput, 'Zip must be 5 digits.', false);
        });

        // Expiry formatting MM/YY
        expiryInput.addEventListener('input', () => {
            let v = expiryInput.value.replace(/[^\d]/g, '');
            if (v.length > 4) v = v.slice(0, 4);
            if (v.length > 2) v = v.slice(0, 2) + '/' + v.slice(2);
            expiryInput.value = v;
            setError(expiryInput, 'Invalid expiry format (MM/YY).', false);
        });

        function validExpiry(value) {
            if (!/^\d{2}\/\d{2}$/.test(value)) return false;
            const [mm, yy] = value.split('/').map(s => parseInt(s, 10));
            if (mm < 1 || mm > 12) return false;
            // expiry month must be after current month
            const now = new Date();
            const year = 2000 + yy;
            const expiry = new Date(year, mm - 1 + 1, 1);
            return expiry > now;
        }

        /* -------------------------
           block non-digit keys for numeric fields (nice-to-have)
           ------------------------- */
        [cardNumberInput, cvvInput, zipInput].forEach(el => {
            el.addEventListener('keydown', (e) => {
                const allowedKeys = ['Backspace', 'ArrowLeft', 'ArrowRight', 'Delete', 'Tab'];
                if (allowedKeys.includes(e.key)) return;
                if ((e.ctrlKey || e.metaKey) && ['a', 'c', 'v', 'x', 'A', 'C', 'V', 'X'].includes(e.key)) return;
                if (!/^\d$/.test(e.key)) e.preventDefault();
            });
        });

        /* -------------------------
           Populate states and cities (keep your map code)
           ------------------------- */
        // ... paste your existing populateStates() and state change handler here ...
        // (I assumed you already had stateNames and stateCityMap earlier in the page)



        /* -------------------------
           Form submit validation (keep your existing logic)
           ------------------------- */
        // form.addEventListener('submit', (ev) => {
        //     ev.preventDefault();
        //     let ok = true;



        //     if (!validExpiry(expiryInput.value)) {
        //         setError(expiryInput, 'Invalid expiry date. Use MM/YY and ensure card not expired.', true);
        //         ok = false;
        //     } else setError(expiryInput, '', false);

        //     if (!/^\d{5}$/.test(zipInput.value)) {
        //         setError(zipInput, 'Zip must be 5 digits.', true);
        //         ok = false;
        //     } else setError(zipInput, '', false);

        //     if (!ok) {
        //         const firstInvalid = form.querySelector('.invalid');
        //         if (firstInvalid) firstInvalid.focus();
        //         return;
        //     }
        //     form.submit();
        // });

        /* -------------------------
           Initial state: hide details until a type selected.
           Do NOT call applyCardTypeSettings() unless a type exists.
           ------------------------- */
    </script>
</body>

</html>