<?php
session_start();

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: auth-system/login.php');
    exit;
}

// Check if user is customer
if ($_SESSION['user_role'] !== 'customer') {
    header('Location: shop.php');
    exit;
}

// Database connection
require_once __DIR__ . '/config/db.php';

$user_id = $_SESSION['user_id'];

// Get cart items
$cart_query = $connection->prepare("SELECT * FROM cart WHERE user_id = ?");
$cart_query->bind_param("i", $user_id);
$cart_query->execute();
$cart_result = $cart_query->get_result();

$cart_items = [];
$subtotal = 0;
while ($item = $cart_result->fetch_assoc()) {
    $item['item_total'] = $item['price'] * $item['quantity'];
    $subtotal += $item['item_total'];
    $cart_items[] = $item;
}

$shipping = 500;
$tax = round($subtotal * 0.1, 2);
$total = $subtotal + $shipping + $tax;

$page_title = 'Checkout - Real Time Shopping';
include 'header-php.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <style>
        /* ========== RESET & BASE STYLES ========== */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        html, body {
            height: 100%;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f8f9fa;
        }

        body {
            padding: 0;
        }

        /* ========== CONTAINER & LAYOUT ========== */
        .checkout-wrapper {
            padding: 1rem;
        }

        .checkout-container {
            max-width: 100%;
            margin: 0 auto;
            padding: 1rem;
        }

        /* ========== HEADER SECTION ========== */
        .checkout-header {
            background: linear-gradient(135deg, #333 0%, #555 100%);
            color: white;
            padding: 2rem 1.5rem;
            border-radius: 8px;
            margin-bottom: 2rem;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            text-align: center;
        }

        .checkout-header h1 {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }

        .checkout-header p {
            font-size: 1rem;
            opacity: 0.9;
            margin: 0;
        }

        /* ========== MAIN LAYOUT ========== */
        .checkout-layout {
            display: grid;
            grid-template-columns: 1fr;
            gap: 2rem;
            margin-bottom: 2rem;
        }

        @media (min-width: 992px) {
            .checkout-layout {
                grid-template-columns: 2fr 1fr;
            }
        }

        /* ========== FORM SECTION ========== */
        .checkout-form {
            background: white;
            padding: 2rem;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        }

        .form-section {
            margin-bottom: 2rem;
            padding-bottom: 1.5rem;
            border-bottom: 2px solid #e0e0e0;
        }

        .form-section:last-of-type {
            border-bottom: none;
        }

        .form-section h3 {
            font-size: 1.2rem;
            margin-bottom: 1.5rem;
            color: #333;
            font-weight: 700;
        }

        .form-group {
            margin-bottom: 1.25rem;
        }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: #333;
            font-weight: 600;
            font-size: 0.95rem;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 0.95rem;
            font-family: inherit;
            transition: all 0.3s ease;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #d4a574;
            box-shadow: 0 0 0 3px rgba(212, 165, 116, 0.1);
            background-color: #fafafa;
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr;
            gap: 1rem;
        }

        @media (min-width: 576px) {
            .form-row {
                grid-template-columns: 1fr 1fr;
            }
        }

        /* ========== SHIPPING SECTION ========== */
        .form-check {
            display: flex;
            align-items: center;
            margin-bottom: 1.5rem;
            padding: 1rem;
            background: #f8f9fa;
            border-radius: 6px;
            cursor: pointer;
        }

        .form-check input {
            margin-right: 0.75rem;
            width: 18px;
            height: 18px;
            cursor: pointer;
        }

        .form-check label {
            margin: 0;
            font-weight: 500;
            cursor: pointer;
        }

        .shipping-address-section {
            display: none;
        }

        .shipping-address-section.active {
            display: block;
            padding: 1rem;
            background: #f8f9fa;
            border-radius: 6px;
            margin-bottom: 1rem;
        }

        .shipping-address-section h3 {
            margin-top: 0;
            margin-bottom: 1rem;
        }

        /* ========== PAYMENT METHODS ========== */
        .payment-methods {
            display: grid;
            grid-template-columns: 1fr;
            gap: 1rem;
            margin-top: 1rem;
        }

        .payment-method {
            padding: 1.25rem;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            background: white;
        }

        .payment-method:hover {
            background: #f9f9f9;
            border-color: #d4a574;
        }

        .payment-method input[type="radio"] {
            margin-right: 0.75rem;
            cursor: pointer;
            width: 18px;
            height: 18px;
        }

        .payment-method label {
            margin: 0;
            font-weight: 600;
            cursor: pointer;
        }

        .payment-method.selected {
            background: #e8f5e9;
            border-color: #d4a574;
        }

        .payment-method p {
            margin: 0.75rem 0 0 2rem;
            font-size: 0.85rem;
            color: #666;
        }

        /* ========== PAYMENT FORMS ========== */
        .payment-forms-container {
            margin-top: 1.5rem;
            padding: 1.5rem;
            background: #f9f9f9;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            animation: slideDown 0.3s ease;
        }

        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .payment-form {
            display: none;
            animation: fadeIn 0.3s ease;
        }

        .payment-form.active {
            display: block;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
            }
            to {
                opacity: 1;
            }
        }

        .payment-form-title {
            font-size: 1.1rem;
            font-weight: 700;
            color: #333;
            margin-bottom: 1rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid #d4a574;
        }

        .payment-info-box {
            padding: 1rem;
            border-radius: 6px;
            margin: 1rem 0;
            font-size: 0.9rem;
            line-height: 1.6;
            display: flex;
            align-items: flex-start;
            gap: 0.75rem;
            background: #e3f2fd;
            color: #1565c0;
            border-left: 4px solid #1976d2;
        }

        .payment-info-box.success {
            background: #e8f5e9;
            color: #2e7d32;
            border-left-color: #4caf50;
        }

        .payment-info-box.info {
            background: #fff3e0;
            color: #e65100;
            border-left-color: #ff9800;
        }

        .payment-info-box i {
            margin-top: 2px;
            flex-shrink: 0;
        }

        .field-error {
            display: block;
            color: #d32f2f;
            font-size: 0.8rem;
            margin-top: 0.25rem;
            min-height: 1.2rem;
        }

        .form-group input.error,
        .form-group select.error {
            border-color: #d32f2f !important;
            background-color: #ffebee !important;
        }

        .form-group input:valid:not([type="checkbox"]):not([type="radio"]) {
            border-color: #4caf50;
        }

        .form-group input:focus {
            border-color: #d4a574;
            box-shadow: 0 0 0 3px rgba(212, 165, 116, 0.1);
        }

        /* ========== UPI PAYMENT STYLES ========== */
        .upi-qr-container {
            display: flex;
            justify-content: center;
            margin: 2rem 0;
        }

        .upi-qr-box {
            background: white;
            padding: 2rem;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            text-align: center;
            max-width: 320px;
        }

        .upi-qr-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: #333;
            margin-bottom: 1rem;
        }

        .upi-qr-image {
            width: 250px;
            height: 250px;
            border: 2px solid #d4a574;
            border-radius: 8px;
            margin-bottom: 1.5rem;
            background: #f9f9f9;
        }

        .upi-amount-display {
            background: linear-gradient(135deg, #d4a574 0%, #b8905a 100%);
            color: white;
            padding: 1rem;
            border-radius: 8px;
            margin-top: 1rem;
        }

        .upi-amount-label {
            font-size: 0.85rem;
            opacity: 0.9;
            margin-bottom: 0.5rem;
        }

        .upi-amount-value {
            font-size: 1.8rem;
            font-weight: 700;
        }

        .upi-payment-options {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1rem;
            margin: 1.5rem 0;
        }

        .upi-pay-btn, .upi-manual-btn {
            padding: 1rem;
            border: none;
            border-radius: 6px;
            font-weight: 600;
            font-size: 0.95rem;
            cursor: pointer;
            transition: all 0.3s ease;
            white-space: nowrap;
        }

        .upi-pay-btn {
            background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
            color: white;
        }

        .upi-pay-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(76, 175, 80, 0.3);
        }

        .upi-manual-btn {
            background: #e8f5e9;
            color: #2e7d32;
            border: 2px solid #4CAF50;
        }

        .upi-manual-btn:hover {
            background: #c8e6c9;
        }

        .upi-status {
            background: #e3f2fd;
            border-left: 4px solid #2196F3;
            padding: 1.5rem;
            border-radius: 4px;
            margin: 1.5rem 0;
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .upi-status-icon {
            font-size: 2rem;
            animation: spin 2s linear infinite;
        }

        .upi-status.success {
            background: #e8f5e9;
            border-left-color: #4CAF50;
        }

        .upi-status.success .upi-status-icon {
            animation: none;
            font-size: 1.5rem;
        }

        .upi-status.error {
            background: #ffebee;
            border-left-color: #f44336;
        }

        .upi-status.error .upi-status-icon {
            animation: none;
            font-size: 1.5rem;
        }

        .upi-status-text {
            font-size: 0.95rem;
            color: #333;
        }

        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }

        @media (max-width: 640px) {
            .upi-payment-options {
                grid-template-columns: 1fr;
            }
            
            .upi-qr-image {
                width: 200px;
                height: 200px;
            }
        }

        /* ========== BUTTONS ========== */
        .btn-checkout {
            width: 100%;
            padding: 1rem;
            background: linear-gradient(135deg, #d4a574 0%, #b8905a 100%);
            color: white;
            border: none;
            border-radius: 6px;
            font-weight: 700;
            font-size: 1rem;
            cursor: pointer;
            margin-top: 2rem;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
            min-height: 50px;
        }

        .btn-checkout:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 8px 16px rgba(212, 165, 116, 0.3);
        }

        .btn-checkout:active:not(:disabled) {
            transform: translateY(0);
        }

        .btn-checkout:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        .loading {
            display: none;
        }

        .loading.active {
            display: inline-block;
        }

        /* ========== ORDER SUMMARY SIDEBAR ========== */
        .order-summary {
            background: white;
            padding: 2rem;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            height: fit-content;
            position: static;
            top: 120px;
        }

        .summary-header {
            font-size: 1.2rem;
            font-weight: 700;
            color: #333;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 2px solid #e0e0e0;
        }

        .cart-items {
            display: grid;
            gap: 1rem;
            margin-bottom: 1.5rem;
        }

        .cart-item {
            display: grid;
            grid-template-columns: 70px 1fr;
            gap: 1rem;
            padding: 1rem;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            background: #f8f9fa;
            transition: all 0.3s ease;
        }

        .cart-item:hover {
            border-color: #d4a574;
            background: white;
        }

        .cart-item img {
            width: 70px;
            height: 70px;
            object-fit: cover;
            border-radius: 4px;
        }

        .cart-item-info {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        .cart-item-name {
            font-weight: 600;
            color: #333;
            font-size: 0.95rem;
            line-height: 1.3;
        }

        .cart-item-price {
            color: #666;
            font-size: 0.85rem;
        }

        .cart-item-total {
            color: #d4a574;
            font-weight: 700;
            font-size: 1rem;
        }

        .summary-divider {
            border-top: 1px solid #e0e0e0;
            margin: 1rem 0;
            padding: 0;
        }

        .summary-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.75rem 0;
            font-size: 0.95rem;
            color: #666;
        }

        .summary-row span:last-child {
            font-weight: 600;
            color: #333;
            text-align: right;
        }

        .summary-total {
            padding: 1rem 0;
            font-size: 1.25rem;
            font-weight: 700;
            color: #d4a574;
            display: flex;
            justify-content: space-between;
            border-top: 2px solid #e0e0e0;
            margin-top: 0.5rem;
        }

        .continue-shopping-btn {
            display: block;
            width: 100%;
            padding: 0.75rem;
            margin-top: 1.5rem;
            text-align: center;
            padding: 0.75rem;
            border: 1px solid #ddd;
            border-radius: 6px;
            text-decoration: none;
            color: #333;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .continue-shopping-btn:hover {
            background: #f8f9fa;
            border-color: #d4a574;
            color: #d4a574;
        }

        /* ========== ALERTS ========== */
        .alert {
            padding: 1.5rem;
            border-radius: 8px;
            margin-bottom: 2rem;
            border-left: 4px solid;
        }

        .alert-info {
            background: #d1ecf1;
            color: #0c5460;
            border-color: #bee5eb;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border-color: #f5c6cb;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border-color: #c3e6cb;
        }

        .alert a {
            color: inherit;
            font-weight: 600;
            text-decoration: underline;
        }

        /* ========== TOAST NOTIFICATIONS ========== */
        .toast {
            position: fixed;
            top: 1rem;
            right: 1rem;
            padding: 1rem 1.5rem;
            color: white;
            border-radius: 6px;
            z-index: 9999;
            display: none;
            font-weight: 600;
            animation: slideIn 0.3s ease-out;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            max-width: 90%;
        }

        .toast.success {
            background: #28a745;
        }

        .toast.error {
            background: #dc3545;
        }

        @keyframes slideIn {
            from {
                transform: translateX(400px);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        /* ========== MODAL STYLES ========== */
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.7);
            z-index: 10000;
            justify-content: center;
            align-items: center;
            padding: 1rem;
        }

        .modal-overlay.active {
            display: flex;
        }

        .modal-content {
            background: white;
            padding: 3rem 2rem;
            border-radius: 12px;
            max-width: 500px;
            width: 100%;
            box-shadow: 0 10px 40px rgba(0,0,0,0.3);
            text-align: center;
            animation: modalSlide 0.4s ease;
        }

        @keyframes modalSlide {
            from {
                transform: scale(0.9);
                opacity: 0;
            }
            to {
                transform: scale(1);
                opacity: 1;
            }
        }

        .modal-success-icon {
            font-size: 3.5rem;
            margin-bottom: 1rem;
            animation: bounce 0.6s ease;
        }

        @keyframes bounce {
            0%, 100% {
                transform: translateY(0);
            }
            50% {
                transform: translateY(-10px);
            }
        }

        .modal-content h2 {
            color: #28a745;
            font-size: 1.75rem;
            margin-bottom: 0.75rem;
            font-weight: 700;
        }

        .modal-content p {
            color: #666;
            font-size: 0.95rem;
            margin-bottom: 1rem;
            line-height: 1.6;
        }

        .order-id-box {
            background: #f0f0f0;
            padding: 1.25rem;
            border-radius: 8px;
            margin: 1.5rem 0;
            border-left: 4px solid #d4a574;
        }

        .order-id-box .label {
            color: #666;
            font-size: 0.75rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .order-id-box .value {
            color: #333;
            font-size: 1.5rem;
            font-weight: 700;
            margin-top: 0.5rem;
        }

        .order-total-box {
            background: #e8f5e9;
            padding: 1.25rem;
            border-radius: 8px;
            margin: 1.5rem 0;
        }

        .order-total-box .label {
            color: #27ae60;
            font-size: 0.75rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .order-total-box .value {
            color: #27ae60;
            font-size: 1.5rem;
            font-weight: 700;
            margin-top: 0.5rem;
        }

        .modal-buttons {
            display: grid;
            grid-template-columns: 1fr;
            gap: 0.75rem;
            margin-top: 2rem;
        }

        @media (min-width: 400px) {
            .modal-buttons {
                grid-template-columns: 1fr 1fr;
            }
        }

        .modal-buttons button {
            padding: 0.75rem 1rem;
            border: none;
            border-radius: 6px;
            font-weight: 700;
            cursor: pointer;
            font-size: 0.95rem;
            transition: all 0.3s ease;
        }

        .btn-continue {
            background: #28a745;
            color: white;
        }

        .btn-continue:hover {
            background: #218838;
            transform: translateY(-2px);
        }

        .btn-view {
            background: #d4a574;
            color: white;
        }

        .btn-view:hover {
            background: #b8905a;
            transform: translateY(-2px);
        }

        /* ========== RESPONSIVE ADJUSTMENTS ========== */
        @media (max-width: 1024px) {
            .checkout-container {
                max-width: 100%;
            }

            .checkout-layout {
                gap: 1.5rem;
            }
        }

        @media (max-width: 991px) {
            .checkout-layout {
                grid-template-columns: 1fr;
            }

            .order-summary {
                position: static;
                top: auto;
            }
        }

        @media (max-width: 767px) {
            .checkout-wrapper {
                padding: 0.75rem;
                margin-top: 80px;
            }

            .checkout-container {
                padding: 0.5rem;
            }

            .checkout-header {
                padding: 1.5rem 1rem;
                margin-bottom: 1.5rem;
                border-radius: 6px;
            }

            .checkout-header h1 {
                font-size: 1.5rem;
                margin-bottom: 0.25rem;
            }

            .checkout-header p {
                font-size: 0.95rem;
            }

            .checkout-form,
            .order-summary {
                padding: 1.25rem;
                border-radius: 6px;
            }

            .form-section {
                margin-bottom: 1.5rem;
                padding-bottom: 1rem;
                border-bottom: 1px solid #e0e0e0;
            }

            .form-section h3 {
                font-size: 1.1rem;
                margin-bottom: 1rem;
            }

            .form-group {
                margin-bottom: 1rem;
            }

            .form-group label {
                font-size: 0.9rem;
            }

            .form-group input,
            .form-group select,
            .form-group textarea {
                padding: 0.65rem;
                font-size: 0.9rem;
            }

            .form-row {
                gap: 0.75rem;
            }

            .btn-checkout {
                padding: 0.75rem;
                font-size: 0.95rem;
                min-height: 44px;
            }

            .cart-item {
                grid-template-columns: 70px 1fr;
                gap: 0.75rem;
                padding: 0.75rem;
            }

            .cart-item img {
                width: 70px;
                height: 70px;
            }

            .cart-item-name {
                font-size: 0.9rem;
            }

            .cart-item-price {
                font-size: 0.85rem;
            }

            .cart-item-total {
                font-size: 0.95rem;
            }

            .summary-header {
                font-size: 1.05rem;
            }

            .summary-row {
                font-size: 0.9rem;
                padding: 0.6rem 0;
            }

            .summary-total {
                font-size: 1.05rem;
                padding: 0.75rem 0;
            }

            .payment-method {
                padding: 1rem;
            }

            .payment-method p {
                margin: 0.5rem 0 0 2rem;
                font-size: 0.8rem;
            }

            .modal-content {
                padding: 2rem 1.5rem;
                border-radius: 10px;
            }

            .modal-success-icon {
                font-size: 3rem;
                margin-bottom: 0.75rem;
            }

            .modal-content h2 {
                font-size: 1.5rem;
                margin-bottom: 0.5rem;
            }

            .modal-content p {
                font-size: 0.9rem;
                margin-bottom: 0.75rem;
            }

            .toast {
                top: auto;
                bottom: 1rem;
                left: 0.75rem;
                right: 0.75rem;
                font-size: 0.9rem;
                padding: 0.75rem 1rem;
            }
        }

        @media (max-width: 480px) {
            .checkout-wrapper {
                padding: 0.5rem;
                margin-top: 0px;
            }

            .checkout-container {
                padding: 0.25rem;
            }

            .checkout-header {
                padding: 1.25rem 0.75rem;
                margin-bottom: 1rem;
                border-radius: 6px;
            }

            .checkout-header h1 {
                font-size: 1.25rem;
            }

            .checkout-header p {
                font-size: 0.85rem;
            }

            .checkout-form,
            .order-summary {
                padding: 1rem;
                border-radius: 6px;
            }

            .checkout-layout {
                gap: 1rem;
            }

            .form-section {
                margin-bottom: 1.25rem;
                padding-bottom: 0.75rem;
            }

            .form-section h3 {
                font-size: 1rem;
                margin-bottom: 0.75rem;
            }

            .form-group {
                margin-bottom: 0.75rem;
            }

            .form-group label {
                font-size: 0.85rem;
                margin-bottom: 0.35rem;
            }

            .form-group input,
            .form-group select,
            .form-group textarea {
                padding: 0.6rem;
                font-size: 0.85rem;
                border-radius: 4px;
            }

            .form-row {
                grid-template-columns: 1fr;
                gap: 0.65rem;
            }

            .form-check {
                padding: 0.75rem;
                margin-bottom: 1rem;
            }

            .form-check input {
                width: 16px;
                height: 16px;
            }

            .form-check label {
                font-size: 0.9rem;
            }

            .shipping-address-section {
                padding: 0.75rem;
                margin-bottom: 0.75rem;
            }

            .shipping-address-section h3 {
                font-size: 0.95rem;
                margin-bottom: 0.5rem;
            }

            .payment-methods {
                grid-template-columns: 1fr;
                gap: 0.75rem;
            }

            .payment-method {
                padding: 0.75rem;
                border-radius: 4px;
            }

            .payment-method input {
                width: 16px;
                height: 16px;
            }

            .payment-method label {
                font-size: 0.9rem;
            }

            .payment-method p {
                margin: 0.4rem 0 0 1.75rem;
                font-size: 0.75rem;
            }

            .btn-checkout {
                padding: 0.65rem 1rem;
                font-size: 0.9rem;
                margin-top: 1.5rem;
            }

            .cart-item {
                grid-template-columns: 60px 1fr;
                gap: 0.6rem;
                padding: 0.65rem;
                border-radius: 4px;
            }

            .cart-item img {
                width: 60px;
                height: 60px;
                border-radius: 3px;
            }

            .cart-item-name {
                font-size: 0.85rem;
                line-height: 1.2;
            }

            .cart-item-price {
                font-size: 0.8rem;
            }

            .cart-item-total {
                font-size: 0.9rem;
            }

            .summary-header {
                font-size: 0.95rem;
                margin-bottom: 0.75rem;
                padding-bottom: 0.5rem;
            }

            .summary-divider {
                margin: 0.5rem 0;
            }

            .summary-row {
                font-size: 0.8rem;
                padding: 0.5rem 0;
            }

            .summary-total {
                font-size: 0.95rem;
                padding: 0.65rem 0;
                margin-top: 0.25rem;
            }

            .alert {
                padding: 1rem 0.75rem;
                font-size: 0.9rem;
                border-left-width: 3px;
            }

            .modal-content {
                padding: 1.5rem 1rem;
                width: 95%;
            }

            .modal-success-icon {
                font-size: 2.5rem;
                margin-bottom: 0.5rem;
            }

            .modal-content h2 {
                font-size: 1.25rem;
                margin-bottom: 0.4rem;
            }

            .modal-content p {
                font-size: 0.85rem;
                margin-bottom: 0.5rem;
            }

            .order-id-box {
                padding: 1rem;
                margin: 1rem 0;
                border-left-width: 3px;
            }

            .order-id-box .label {
                font-size: 0.7rem;
            }

            .order-id-box .value {
                font-size: 1.25rem;
                margin-top: 0.35rem;
            }

            .order-total-box {
                padding: 1rem;
                margin: 1rem 0;
            }

            .order-total-box .label {
                font-size: 0.7rem;
            }

            .order-total-box .value {
                font-size: 1.25rem;
                margin-top: 0.35rem;
            }

            .modal-buttons {
                gap: 0.5rem;
                margin-top: 1.5rem;
            }

            .modal-buttons button {
                padding: 0.65rem 0.75rem;
                font-size: 0.85rem;
            }

            .toast {
                bottom: 0.75rem;
                left: 0.5rem;
                right: 0.5rem;
                padding: 0.65rem 0.8rem;
                font-size: 0.8rem;
            }
        }

        @media (max-width: 360px) {
            .checkout-header h1 {
                font-size: 1.1rem;
            }

            .checkout-header p {
                font-size: 0.8rem;
            }

            .checkout-form,
            .order-summary {
                padding: 0.75rem;
            }

            .form-section h3 {
                font-size: 0.9rem;
            }

            .form-group label {
                font-size: 0.8rem;
            }

            .form-group input,
            .form-group select,
            .form-group textarea {
                font-size: 0.8rem;
                padding: 0.55rem;
            }

            .btn-checkout {
                padding: 0.6rem 0.75rem;
                font-size: 0.85rem;
                margin-top: 1rem;
            }

            .cart-item {
                grid-template-columns: 55px 1fr;
                gap: 0.5rem;
                padding: 0.5rem;
            }

            .cart-item img {
                width: 55px;
                height: 55px;
            }

            .cart-item-name {
                font-size: 0.8rem;
            }

            .summary-row {
                font-size: 0.75rem;
            }

            .summary-total {
                font-size: 0.85rem;
            }

            .modal-buttons {
                grid-template-columns: 1fr;
            }

            .modal-buttons button {
                padding: 0.55rem 0.6rem;
                font-size: 0.8rem;
            }
        }

        /* ========== PRINT STYLES ========== */
        @media print {
            .btn-checkout,
            .toast,
            .modal-overlay {
                display: none;
            }

            .form-section {
                page-break-inside: avoid;
            }
        }
    </style>
</head>
<body>
    <!-- Toast Notification -->
    <div class="toast" id="toast"></div>

    <!-- Order Confirmation Modal -->
    <div class="modal-overlay" id="confirmationModal">
        <div class="modal-content">
            <div class="modal-success-icon">✅</div>
            <h2>Order Confirmed!</h2>
            <p>Your order has been placed successfully. We'll send you a confirmation email shortly.</p>
            
            <div class="order-id-box">
                <div class="label">Order Number</div>
                <div class="value" id="modalOrderId">#1001</div>
            </div>

            <div class="order-total-box">
                <div class="label">Total Amount</div>
                <div class="value" id="modalOrderTotal">Rs. 0</div>
            </div>

            <p style="color: #999; font-size: 0.85rem; margin-top: 1rem;">
                You can track your order status anytime from your account.
            </p>

            <div class="modal-buttons">
                <button class="btn-continue" onclick="goToOrders()">View My Orders</button>
                <button class="btn-view" onclick="continueShopping()">Continue Shopping</button>
            </div>
        </div>
    </div>

    <!-- Main Checkout Container -->
    <div class="checkout-wrapper">
        <div class="checkout-container">
            <!-- Header -->
            <div class="checkout-header">
                <h1>🛒 Checkout</h1>
                <p>Complete your purchase securely</p>
            </div>

            <!-- Empty Cart Alert -->
            <?php if (empty($cart_items)): ?>
                <div class="alert alert-info">
                    Your cart is empty. <a href="shop.php">Continue shopping</a>
                </div>
            <?php else: ?>
                <!-- Checkout Layout -->
                <div class="checkout-layout">
                    <!-- Checkout Form -->
                    <div class="checkout-form">
                    <form id="checkoutForm">
                        <!-- Billing Details -->
                        <div class="form-section">
                            <h3>📍 Billing Address</h3>
                            <div class="form-row">
                                <div class="form-group">
                                    <label>First Name *</label>
                                    <input type="text" name="first_name" required>
                                </div>
                                <div class="form-group">
                                    <label>Last Name *</label>
                                    <input type="text" name="last_name" required>
                                </div>
                            </div>
                            <div class="form-group">
                                <label>Company (Optional)</label>
                                <input type="text" name="company">
                            </div>
                            <div class="form-group">
                                <label>Country *</label>
                                <select name="country" required>
                                    <option value="">Select Country</option>
                                    <option value="India">India</option>
                                    <option value="Pakistan">Pakistan</option>
                                    <option value="United Kingdom">United Kingdom</option>
                                    <option value="United States">United States</option>
                                    <option value="Australia">Australia</option>
                                    <option value="Germany">Germany</option>
                                    <option value="Canada">Canada</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>Street Address *</label>
                                <input type="text" name="address" placeholder="House number and street name" required>
                            </div>
                            <div class="form-group">
                                <label>City *</label>
                                <input type="text" name="city" required>
                            </div>
                            <div class="form-row">
                                <div class="form-group">
                                    <label>Postcode / ZIP *</label>
                                    <input type="text" name="postcode" required>
                                </div>
                                <div class="form-group">
                                    <label>Email *</label>
                                    <input type="email" name="email" required>
                                </div>
                            </div>
                            <div class="form-group">
                                <label>Phone *</label>
                                <input type="tel" name="phone" required>
                            </div>
                        </div>

                        <!-- Shipping Address -->
                        <div class="form-section">
                            <div class="form-check">
                                <input type="checkbox" id="ship_to_different" name="ship_to_different" value="1">
                                <label for="ship_to_different">Ship to a different address?</label>
                            </div>

                            <div class="shipping-address-section" id="shippingAddressSection">
                                <h3 style="margin-top: 20px;">📦 Shipping Address</h3>
                                <div class="form-row">
                                    <div class="form-group">
                                        <label>First Name</label>
                                        <input type="text" name="shipping_first_name">
                                    </div>
                                    <div class="form-group">
                                        <label>Last Name</label>
                                        <input type="text" name="shipping_last_name">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label>Country</label>
                                    <select name="shipping_country">
                                        <option value="">Select Country</option>
                                        <option value="Pakistan">Pakistan</option>
                                        <option value="United Kingdom">United Kingdom</option>
                                        <option value="United States">United States</option>
                                        <option value="Australia">Australia</option>
                                        <option value="Germany">Germany</option>
                                        <option value="Canada">Canada</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label>Street Address</label>
                                    <input type="text" name="shipping_address">
                                </div>
                                <div class="form-group">
                                    <label>City</label>
                                    <input type="text" name="shipping_city">
                                </div>
                                <div class="form-row">
                                    <div class="form-group">
                                        <label>Postcode / ZIP</label>
                                        <input type="text" name="shipping_postcode">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Additional Information -->
                        <div class="form-section">
                            <h3>📝 Order Notes (Optional)</h3>
                            <div class="form-group">
                                <label>Order Notes</label>
                                <textarea name="order_notes" rows="4" placeholder="Notes about your order, e.g. special notes for delivery"></textarea>
                            </div>
                        </div>

                        <!-- Payment Method -->
                        <div class="form-section">
                            <h3>💳 Payment Method</h3>
                            <div class="payment-methods">
                                <!-- Credit Card -->
                                <div class="payment-method selected" data-method="credit_card">
                                    <input type="radio" name="payment_method" value="credit_card" checked>
                                    <label style="margin: 0;">💳 Credit Card</label>
                                    <p style="margin: 10px 0 0 30px; font-size: 12px; color: #666;">Secure payment via credit card</p>
                                </div>

                                <!-- PayPal -->
                                <div class="payment-method" data-method="paypal">
                                    <input type="radio" name="payment_method" value="paypal">
                                    <label style="margin: 0;">🅿️ PayPal</label>
                                    <p style="margin: 10px 0 0 30px; font-size: 12px; color: #666;">Secure payment via PayPal</p>
                                </div>

                                <!-- Bank Transfer -->
                                <div class="payment-method" data-method="bank_transfer">
                                    <input type="radio" name="payment_method" value="bank_transfer">
                                    <label style="margin: 0;">🏦 Bank Transfer</label>
                                    <p style="margin: 10px 0 0 30px; font-size: 12px; color: #666;">Direct bank transfer to our account</p>
                                </div>

                                <!-- Cash on Delivery -->
                                <div class="payment-method" data-method="cod">
                                    <input type="radio" name="payment_method" value="cod">
                                    <label style="margin: 0;">💰 Cash on Delivery</label>
                                    <p style="margin: 10px 0 0 30px; font-size: 12px; color: #666;">Pay when you receive your order</p>
                                </div>
                                <div class="payment-method" data-method="upi"> 
                                    <input type="radio" name="payment_method" value="upi"> 
                                    <label style="margin: 0;">🇮🇳 UPI</label> 
                                    <p style="margin: 10px 0 0 30px; font-size: 12px; color: #666;">Pay via UPI apps (GPay, PhonePe, Paytm)</p> 
                                </div>
                            </div>

                            <!-- Payment Method Forms -->
                            <div class="payment-forms-container">
                                <!-- Credit Card Form -->
                                <div class="payment-form active" id="form-credit_card">
                                    <div class="payment-form-title">Credit Card Details</div>
                                    <!-- Card preview -->
                                    <div class="card-preview" id="cardPreview" aria-hidden="false">
                                        <div class="card-brand" id="cardBrand">
                                            <!-- Inline SVGs toggled by JS -->
                                            <svg id="brand-visa" viewBox="0 0 48 32" style="display:none; width:52px; height:auto;"><rect width="48" height="32" rx="4" fill="#1a1f71"/><text x="24" y="20" fill="#fff" font-size="10" font-weight="700" text-anchor="middle">VISA</text></svg>
                                            <svg id="brand-mc" viewBox="0 0 48 32" style="display:none; width:52px; height:auto;"><rect width="48" height="32" rx="4" fill="#eb001b"/><text x="24" y="20" fill="#fff" font-size="10" font-weight="700" text-anchor="middle">MC</text></svg>
                                            <svg id="brand-amex" viewBox="0 0 48 32" style="display:none; width:52px; height:auto;"><rect width="48" height="32" rx="4" fill="#2e77bb"/><text x="24" y="20" fill="#fff" font-size="8" font-weight="700" text-anchor="middle">AMEX</text></svg>
                                        </div>
                                        <div class="card-front">
                                            <div class="card-chip"></div>
                                            <div class="card-number" id="previewNumber">•••• •••• •••• ••••</div>
                                            <div class="card-name" id="previewName">CARD HOLDER</div>
                                            <div class="card-expiry" id="previewExpiry">MM/YY</div>
                                        </div>
                                    </div>

                                    <style>
                                    /* Card preview styles */
                                    .card-preview{width:100%;max-width:420px;margin:0 0 1rem 0;padding:14px;border-radius:12px;background:linear-gradient(135deg,#1f2937,#111827);color:#fff;display:flex;gap:12px;align-items:center}
                                    .card-front{flex:1;position:relative;padding:12px}
                                    .card-chip{width:40px;height:28px;background:linear-gradient(90deg,#f3f4f6,#e5e7eb);border-radius:4px;margin-bottom:12px}
                                    .card-number{font-family:monospace;font-size:18px;letter-spacing:2px;margin-bottom:8px}
                                    .card-name{font-size:12px;text-transform:uppercase;color:#cbd5e1}
                                    .card-expiry{position:absolute;right:12px;bottom:12px;font-size:12px;color:#cbd5e1}
                                    .card-brand{width:56px;flex-shrink:0}
                                    </style>

                                    <div class="form-group">
                                        <label>Card Holder Name *</label>
                                        <input type="text" name="card_holder" placeholder="John Doe" class="card-field">
                                        <span class="field-error" id="error-card_holder"></span>
                                    </div>
                                    <div class="form-group">
                                        <label>Card Number *</label>
                                        <input type="text" name="card_number" placeholder="1234 5678 9012 3456" maxlength="19" class="card-field">
                                        <span class="field-error" id="error-card_number"></span>
                                    </div>
                                    <div class="form-row">
                                        <div class="form-group">
                                            <label>Expiry Date (MM/YY) *</label>
                                            <input type="text" name="card_expiry" placeholder="12/25" maxlength="5" class="card-field">
                                            <span class="field-error" id="error-card_expiry"></span>
                                        </div>
                                        <div class="form-group">
                                            <label>CVV *</label>
                                            <input type="text" name="card_cvv" placeholder="123" maxlength="4" class="card-field">
                                            <span class="field-error" id="error-card_cvv"></span>
                                        </div>
                                    </div>
                                </div>

                                <!-- PayPal Form -->
                                <div class="payment-form" id="form-paypal">
                                    <div class="payment-form-title">PayPal Account</div>
                                    <div class="form-group">
                                        <label>PayPal Email *</label>
                                        <input type="email" name="paypal_email" placeholder="your.email@paypal.com" class="paypal-field">
                                        <span class="field-error" id="error-paypal_email"></span>
                                    </div>
                                    <div class="payment-info-box">
                                        <i class="fa-solid fa-info-circle"></i> You will be redirected to PayPal to complete your payment securely.
                                    </div>
                                </div>

                                <!-- Bank Transfer Form -->
                                <div class="payment-form" id="form-bank_transfer">
                                    <div class="payment-form-title">Bank Transfer Details</div>
                                    <div class="payment-info-box success">
                                        <strong>Bank Transfer Information:</strong><br>
                                        Account Name: Interior Design Inc.<br>
                                        Account Number: 1234567890<br>
                                        Bank Code: XXXX<br>
                                        SWIFT Code: XXXXX<br><br>
                                        <em>Please mention your order number as reference.</em>
                                    </div>
                                    <div class="form-group">
                                        <label><input type="checkbox" name="bank_transfer_confirm" class="bank-field"> I confirm I will transfer the amount</label>
                                        <span class="field-error" id="error-bank_transfer_confirm"></span>
                                    </div>
                                </div>

                                <!-- Cash on Delivery Form -->
                                <div class="payment-form" id="form-cod">
                                    <div class="payment-form-title">Delivery Information</div>
                                    <div class="payment-info-box info">
                                        <strong>Cash on Delivery Terms:</strong><br>
                                        • You can pay in cash when the delivery arrives at your address<br>
                                        • Our delivery partner will collect the payment<br>
                                        • Make sure to have exact or close amount ready<br>
                                        • Keep your phone accessible for delivery confirmation
                                    </div>
                                    <div class="form-group">
                                        <label><input type="checkbox" name="cod_confirm" class="cod-field"> I understand and agree to pay on delivery</label>
                                        <span class="field-error" id="error-cod_confirm"></span>
                                    </div>
                                </div>

                                <!-- UPI Payment Form -->
                                <div class="payment-form" id="form-upi">
                                    <div class="payment-form-title">🇮🇳 UPI Payment</div>
                                    
                                    <!-- QR Code Display -->
                                    <div class="upi-qr-container">
                                        <div class="upi-qr-box">
                                            <div class="upi-qr-title">Scan to Pay</div>
                                            <img id="upiQrCode" src="" alt="UPI QR Code" class="upi-qr-image">
                                            <div class="upi-amount-display">
                                                <div class="upi-amount-label">Amount to Pay:</div>
                                                <div class="upi-amount-value" id="upiAmount">Rs. <?php echo number_format($total, 0); ?></div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- UPI ID Input -->
                                    <div class="form-group">
                                        <label>Your UPI ID (Optional) *</label>
                                        <input type="text" name="upi_id" placeholder="example@upi" class="upi-field">
                                        <span class="field-error" id="error-upi_id"></span>
                                        <small style="color: #888; margin-top: 5px; display: block;">Enter your UPI ID (e.g., 9876543210@okhdfcbank) or leave empty to scan QR</small>
                                    </div>

                                    <!-- Payment Options -->
                                    <div class="upi-payment-options">
                                        <button type="button" class="upi-pay-btn" id="upiPayBtn">
                                            💳 Open UPI App
                                        </button>
                                        <button type="button" class="upi-manual-btn" id="upiManualBtn">
                                            ✓ Confirm Payment Done
                                        </button>
                                    </div>

                                    <!-- Payment Status -->
                                    <div id="upiPaymentStatus" class="upi-status" style="display: none;">
                                        <div class="upi-status-icon" id="upiStatusIcon">⏳</div>
                                        <div class="upi-status-text" id="upiStatusText">Processing payment...</div>
                                    </div>

                                    <!-- Payment Info -->
                                    <div class="payment-info-box info">
                                        <strong>UPI Payment Instructions:</strong><br>
                                        • Scan the QR code with any UPI app (Google Pay, PhonePe, Paytm)<br>
                                        • OR enter your UPI ID above and click "Open UPI App"<br>
                                        • Complete the payment on your UPI app<br>
                                        • Click "Confirm Payment Done" after successful payment<br>
                                        • Your order will be confirmed instantly
                                    </div>
                                </div>
                            </div>
                        </div>

                        <button type="submit" class="btn-checkout">
                            Place Order <span class="loading" id="loading">⏳...</span>
                        </button>
                    </form>
                </div>

                        <!-- Order Summary -->
                        <div class="order-summary">
                            <div class="summary-header">📦 Order Summary</div>
                            <div class="cart-items">
                            <div class="cart-items">
                                <?php foreach ($cart_items as $item): ?>
                                    <div class="cart-item">
                                        <img src="<?php echo htmlspecialchars($item['image']); ?>" alt="<?php echo htmlspecialchars($item['product_name']); ?>">
                                        <div class="cart-item-info">
                                            <div class="cart-item-name"><?php echo htmlspecialchars($item['product_name']); ?></div>
                                            <div class="cart-item-price">Rs. <?php echo number_format($item['price'], 0); ?> × <?php echo $item['quantity']; ?></div>
                                            <div class="cart-item-total">Rs. <?php echo number_format($item['item_total'], 0); ?></div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>

                            <div class="summary-divider"></div>

                            <div class="summary-row">
                                <span>Subtotal:</span>
                                <span id="subtotal">Rs. <?php echo number_format($subtotal, 0); ?></span>
                            </div>
                            <div class="summary-row">
                                <span>Tax (10%):</span>
                                <span id="tax">Rs. <?php echo number_format($tax, 0); ?></span>
                            </div>
                            <div class="summary-row">
                                <span>Shipping:</span>
                                <span id="shipping">Rs. <?php echo number_format($shipping, 0); ?></span>
                            </div>

                            <div class="summary-divider"></div>

                            <div class="summary-total">
                                <span>Total:</span>
                                <span id="total">Rs. <?php echo number_format($total, 0); ?></span>
                            </div>

                            <a href="shop.php" class="continue-shopping-btn">← Continue Shopping</a>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        // Stripe publishable key from server config (empty or placeholder if not configured)
        <?php @include __DIR__ . '/auth-system/stripe_config.php';
        $pub = isset($stripe_publishable) ? $stripe_publishable : '';
        echo "const STRIPE_PUBLISHABLE_KEY = '" . addslashes($pub) . "';\n";
        ?>

        <?php @include __DIR__ . '/auth-system/paypal_config.php';
        $pp_client = isset($paypal_client_id) ? $paypal_client_id : '';
        $pp_mode = isset($paypal_mode) ? $paypal_mode : 'sandbox';
        echo "const PAYPAL_CLIENT_ID = '" . addslashes($pp_client) . "';\n";
        echo "const PAYPAL_MODE = '" . addslashes($pp_mode) . "';\n";
        ?>

        // Prepare Stripe Elements if key provided
        let stripe = null, elements = null, cardElement = null;
        if (STRIPE_PUBLISHABLE_KEY && STRIPE_PUBLISHABLE_KEY.indexOf('pk_') === 0 && STRIPE_PUBLISHABLE_KEY.indexOf('YOUR_PUBLISHABLE') === -1) {
            const s = document.createElement('script');
            s.src = 'https://js.stripe.com/v3/';
            s.onload = initStripe;
            document.head.appendChild(s);
        }

        function initStripe(){
            try {
                stripe = Stripe(STRIPE_PUBLISHABLE_KEY);
                elements = stripe.elements();
                const style = {
                    base: { color: '#111', fontSize: '16px', '::placeholder': { color: '#aab7c4' } },
                    invalid: { color: '#e5424d' }
                };
                cardElement = elements.create('card', { style: style });
                const container = document.createElement('div'); container.id = 'stripe-card-element'; container.style.padding = '10px 0';
                const creditForm = document.getElementById('form-credit_card');
                if (creditForm) creditForm.insertBefore(container, creditForm.querySelector('.form-group'));
                cardElement.mount('#stripe-card-element');

                // hide raw card input groups (keep preview)
                document.querySelectorAll('input[name="card_number"], input[name="card_expiry"], input[name="card_cvv"]').forEach(i => {
                    const g = i.closest('.form-group'); if (g) g.style.display = 'none';
                });
                // Expose for verification function
                window.stripe = stripe;
                window.cardElement = cardElement;
                // Auto-verify when Stripe Elements reports a complete card
                try {
                    cardElement.on('change', function(evt){
                        if (evt && evt.complete) {
                            // small debounce to avoid duplicate calls
                            if (window._autoVerifyTimer) clearTimeout(window._autoVerifyTimer);
                            window._autoVerifyTimer = setTimeout(function(){
                                triggerAutoVerify();
                            }, 500);
                        }
                    });
                } catch(e) {
                    // ignore
                }
            } catch (e) {
                console.error('Stripe init error', e);
            }
        }

        // Debounced auto-verify trigger for card details (works with Elements or raw inputs)
        function triggerAutoVerify() {
            if (window.paymentMethodVerified) return; // already verified
            if (window._autoVerifyInProgress) return; // already running

            // prefer Elements
            if (window.cardElement && window.stripe) {
                // require card holder name
                const name = (document.querySelector('input[name="card_holder"]')||{value:''}).value || (document.querySelector('input[name="first_name"]')||{value:''}).value;
                if (!name || name.trim().length < 2) return;
                // kick off verification
                window._autoVerifyInProgress = true;
                const vbtn = document.querySelector('.verify-card-btn');
                if (vbtn) { vbtn.textContent = 'Verifying...'; vbtn.disabled = true; vbtn.style.opacity = '0.7'; }
                verifyCard().finally(() => {
                    window._autoVerifyInProgress = false;
                    if (vbtn && !window.paymentMethodVerified) { vbtn.textContent = 'Verify Card'; vbtn.disabled = false; vbtn.style.opacity = '1'; }
                });
                return;
            }

            // fallback: if raw inputs are present, verify when all validations pass
            try {
                const holderValid = validateCardHolder(document.querySelector('input[name="card_holder"]'));
                const numValid = validateCardNumber(document.querySelector('input[name="card_number"]'));
                const expValid = validateCardExpiry(document.querySelector('input[name="card_expiry"]'));
                const cvvValid = validateCardCVV(document.querySelector('input[name="card_cvv"]'));
                if (holderValid && numValid && expValid && cvvValid) {
                    if (window._autoVerifyTimer) clearTimeout(window._autoVerifyTimer);
                    window._autoVerifyTimer = setTimeout(function(){
                        if (!window.paymentMethodVerified && !window._autoVerifyInProgress) {
                            window._autoVerifyInProgress = true;
                            const vbtn = document.querySelector('.verify-card-btn');
                            if (vbtn) { vbtn.textContent = 'Verifying...'; vbtn.disabled = true; vbtn.style.opacity = '0.7'; }
                            verifyCard().finally(() => {
                                window._autoVerifyInProgress = false;
                                if (vbtn && !window.paymentMethodVerified) { vbtn.textContent = 'Verify Card'; vbtn.disabled = false; vbtn.style.opacity = '1'; }
                            });
                        }
                    }, 600);
                }
            } catch(e) {
                // ignore validation errors here
            }
        }
        /**
         * Toggle shipping address section
         */
        document.getElementById('ship_to_different').addEventListener('change', function() {
            const shippingSection = document.getElementById('shippingAddressSection');
            if (this.checked) {
                shippingSection.classList.add('active');
            } else {
                shippingSection.classList.remove('active');
            }
        });

        /**
         * Payment method selection with visual feedback and form switching
         */
        document.querySelectorAll('input[name="payment_method"]').forEach(radio => {
            radio.addEventListener('change', function() {
                // Update visual selection
                document.querySelectorAll('.payment-method').forEach(el => el.classList.remove('selected'));
                this.closest('.payment-method').classList.add('selected');

                // Switch payment form
                const selectedMethod = this.value;
                switchPaymentForm(selectedMethod);
            });
        });

        /**
         * Make payment method divs clickable
         */
        document.querySelectorAll('.payment-method').forEach(method => {
            method.addEventListener('click', function(e) {
                // Don't trigger if clicking on the radio directly
                if (e.target.name === 'payment_method') return;
                
                const radio = this.querySelector('input[type="radio"]');
                radio.checked = true;
                radio.dispatchEvent(new Event('change', { bubbles: true }));
            });

            // Add cursor style
            method.style.cursor = 'pointer';
        });

        /**
         * Switch active payment form
         */
        function switchPaymentForm(method) {
            // Hide all forms
            document.querySelectorAll('.payment-form').forEach(form => {
                form.classList.remove('active');
            });

            // Show selected form
            const selectedForm = document.getElementById('form-' + method);
            if (selectedForm) {
                selectedForm.classList.add('active');
            }

            // Clear previous errors
            clearPaymentErrors();
        }

        /**
         * Clear payment errors
         */
        function clearPaymentErrors() {
            document.querySelectorAll('.field-error').forEach(error => {
                error.textContent = '';
            });
            document.querySelectorAll('.form-group input, .form-group select').forEach(field => {
                field.classList.remove('error');
            });
        }

        /**
         * Real-time validation for credit card
         */
        const cardFields = document.querySelectorAll('.card-field');

        // Card holder name validation
        const cardHolder = document.querySelector('input[name="card_holder"]');
        if (cardHolder) {
            cardHolder.addEventListener('blur', function() {
                validateCardHolder(this);
            });
            cardHolder.addEventListener('input', function() {
                if (this.value.length > 0) validateCardHolder(this);
            });
        }

        // Card number formatting and validation
        const cardNumber = document.querySelector('input[name="card_number"]');
        if (cardNumber) {
            cardNumber.addEventListener('input', function(e) {
                // Remove non-digits
                let value = this.value.replace(/\D/g, '');
                // Add spaces every 4 digits
                let formatted = value.replace(/(\d{4})/g, '$1 ').trim();
                this.value = formatted;

                validateCardNumber(this);
            });
            cardNumber.addEventListener('blur', function() {
                validateCardNumber(this);
            });
        }

        // Expiry date formatting
        const cardExpiry = document.querySelector('input[name="card_expiry"]');
        if (cardExpiry) {
            cardExpiry.addEventListener('input', function(e) {
                let value = this.value.replace(/\D/g, '');
                if (value.length >= 2) {
                    value = value.slice(0, 2) + '/' + value.slice(2, 4);
                }
                this.value = value;

                validateCardExpiry(this);
            });
            cardExpiry.addEventListener('blur', function() {
                validateCardExpiry(this);
            });
        }

        // CVV validation
        const cardCVV = document.querySelector('input[name="card_cvv"]');
        if (cardCVV) {
            cardCVV.addEventListener('input', function(e) {
                this.value = this.value.replace(/\D/g, '').slice(0, 4);
                validateCardCVV(this);
            });
            cardCVV.addEventListener('blur', function() {
                validateCardCVV(this);
            });
        }

        /**
         * Validation functions
         */
        function validateCardHolder(input) {
            const value = input.value.trim();
            const errorEl = document.getElementById('error-card_holder');
            
            if (!value) {
                showError(input, errorEl, 'Card holder name is required');
                return false;
            }
            if (value.length < 3) {
                showError(input, errorEl, 'Card holder name must be at least 3 characters');
                return false;
            }
            if (!/^[a-zA-Z\s]*$/.test(value)) {
                showError(input, errorEl, 'Card holder name can only contain letters');
                return false;
            }
            
            clearError(input, errorEl);
            return true;
        }

        function validateCardNumber(input) {
            const value = input.value.replace(/\s/g, '');
            const errorEl = document.getElementById('error-card_number');
            
            if (!value) {
                showError(input, errorEl, 'Card number is required');
                return false;
            }
            if (value.length !== 16) {
                showError(input, errorEl, 'Card number must be 16 digits');
                return false;
            }
            if (!/^\d+$/.test(value)) {
                showError(input, errorEl, 'Card number must contain only digits');
                return false;
            }

            // Luhn algorithm validation
            if (!luhnCheck(value)) {
                showError(input, errorEl, 'Invalid card number');
                return false;
            }
            
            clearError(input, errorEl);
            return true;
        }

        function validateCardExpiry(input) {
            const value = input.value;
            const errorEl = document.getElementById('error-card_expiry');
            
            if (!value) {
                showError(input, errorEl, 'Expiry date is required');
                return false;
            }
            if (!/^\d{2}\/\d{2}$/.test(value)) {
                showError(input, errorEl, 'Expiry date must be in MM/YY format');
                return false;
            }

            const [month, year] = value.split('/');
            const monthNum = parseInt(month);
            
            if (monthNum < 1 || monthNum > 12) {
                showError(input, errorEl, 'Invalid month');
                return false;
            }

            // Check if card is expired
            const currentYear = new Date().getFullYear() % 100;
            const currentMonth = new Date().getMonth() + 1;
            const expiryYear = parseInt(year);

            if (expiryYear < currentYear || (expiryYear === currentYear && monthNum < currentMonth)) {
                showError(input, errorEl, 'Card has expired');
                return false;
            }
            
            clearError(input, errorEl);
            return true;
        }

        function validateCardCVV(input) {
            const value = input.value;
            const errorEl = document.getElementById('error-card_cvv');
            
            if (!value) {
                showError(input, errorEl, 'CVV is required');
                return false;
            }
            if (!/^\d{3,4}$/.test(value)) {
                showError(input, errorEl, 'CVV must be 3 or 4 digits');
                return false;
            }
            
            clearError(input, errorEl);
            return true;
        }

        /**
         * PayPal email validation
         */
        const paypalEmail = document.querySelector('input[name="paypal_email"]');
        if (paypalEmail) {
            paypalEmail.addEventListener('blur', function() {
                validatePayPalEmail(this);
            });
            paypalEmail.addEventListener('input', function() {
                if (this.value.length > 0) validatePayPalEmail(this);
            });
        }

        function validatePayPalEmail(input) {
            const value = input.value.trim();
            const errorEl = document.getElementById('error-paypal_email');
            
            if (!value) {
                showError(input, errorEl, 'PayPal email is required');
                return false;
            }
            if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
                showError(input, errorEl, 'Please enter a valid email address');
                return false;
            }
            
            clearError(input, errorEl);
            return true;
        }

        /**
         * Helper functions for validation UI
         */
        function showError(input, errorEl, message) {
            input.classList.add('error');
            if (errorEl) {
                errorEl.textContent = message;
            }
        }

        function clearError(input, errorEl) {
            input.classList.remove('error');
            if (errorEl) {
                errorEl.textContent = '';
            }
        }

        /**
         * Luhn algorithm for card number validation
         */
        function luhnCheck(num) {
            let sum = 0;
            let isEven = false;

            for (let i = num.length - 1; i >= 0; i--) {
                let digit = parseInt(num.charAt(i), 10);

                if (isEven) {
                    digit *= 2;
                    if (digit > 9) {
                        digit -= 9;
                    }
                }

                sum += digit;
                isEven = !isEven;
            }

            return sum % 10 === 0;
        }

        /* -------------------- Card preview & brand detection -------------------- */
        function detectCardBrand(number) {
            if (!number) return 'unknown';
            const bin = number.slice(0,2);
            if (/^4/.test(number)) return 'visa';
            if (/^5[1-5]/.test(number) || /^2(2[2-9]|[3-6][0-9]|7[01])/.test(number)) return 'mastercard';
            if (/^3[47]/.test(number)) return 'amex';
            return 'unknown';
        }

        function updateCardPreview() {
            const num = (document.querySelector('input[name="card_number"]')||{value:''}).value.replace(/\s/g,'');
            const name = (document.querySelector('input[name="card_holder"]')||{value:''}).value || '';
            const exp = (document.querySelector('input[name="card_expiry"]')||{value:''}).value || '';

            document.getElementById('previewNumber').textContent = num ? formatPreviewNumber(num) : '•••• •••• •••• ••••';
            document.getElementById('previewName').textContent = name ? name.toUpperCase() : 'CARD HOLDER';
            document.getElementById('previewExpiry').textContent = exp ? exp : 'MM/YY';

            const brand = detectCardBrand(num);
            ['visa','mc','amex'].forEach(b => {
                const el = document.getElementById('brand-' + (b==='mc' ? 'mc' : (b==='visa' ? 'visa' : 'amex')));
                if (!el) return;
                el.style.display = (brand === 'visa' && b==='visa') || (brand === 'mastercard' && b==='mc') || (brand==='amex' && b==='amex') ? 'block' : 'none';
            });
        }

        function formatPreviewNumber(num) {
            // Groups: amex 4-6-5 else 4-4-4-4
            if (/^3[47]/.test(num)) {
                return (num.slice(0,4) + ' ' + (num.slice(4,10)||'') + ' ' + (num.slice(10,15)||'')).trim();
            }
            return num.replace(/(\d{4})/g, '$1 ').trim();
        }

        // Attach listeners to update preview in real time
        ['card_number','card_holder','card_expiry'].forEach(name => {
            const el = document.querySelector('input[name="' + name + '"]');
            if (el) {
                el.addEventListener('input', updateCardPreview);
                el.addEventListener('blur', updateCardPreview);
            }
        });

        // Initialize preview on load
        updateCardPreview();

        /* -------------------- Small 'Verify' actions for other methods -------------------- */
        // PayPal verify: quick client-side email check and visual authenticated state
        function verifyPayPal() {
            const email = document.querySelector('input[name="paypal_email"]').value || '';
            const err = document.getElementById('error-paypal_email');
            if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
                showToast('❌ Enter a valid PayPal email before verification', 'error');
                if (err) err.textContent = 'Enter a valid email';
                return;
            }
            if (err) err.textContent = '';

            if (!PAYPAL_CLIENT_ID || PAYPAL_CLIENT_ID.indexOf('YOUR_PAYPAL') === 0) {
                showToast('PayPal not configured. Please set client id in auth-system/paypal_config.php', 'error');
                return;
            }

            showToast('🔄 Loading PayPal verification...', 'info');

            // Load PayPal SDK if not loaded
            if (typeof paypal === 'undefined') {
                const script = document.createElement('script');
                script.src = 'https://www.paypal.com/sdk/js?client-id=' + encodeURIComponent(PAYPAL_CLIENT_ID) + '&currency=USD&intent=authorize';
                script.onload = renderPayPalModal;
                script.onerror = function() { showToast('❌ Failed to load PayPal SDK', 'error'); };
                document.head.appendChild(script);
            } else {
                renderPayPalModal();
            }

            function renderPayPalModal() {
                // Create modal container
                let wrapper = document.getElementById('paypalVerifyModal');
                if (!wrapper) {
                    wrapper = document.createElement('div');
                    wrapper.id = 'paypalVerifyModal';
                    wrapper.style.position = 'fixed';
                    wrapper.style.left = '0';
                    wrapper.style.top = '0';
                    wrapper.style.width = '100%';
                    wrapper.style.height = '100%';
                    wrapper.style.background = 'rgba(0,0,0,0.6)';
                    wrapper.style.display = 'flex';
                    wrapper.style.alignItems = 'center';
                    wrapper.style.justifyContent = 'center';
                    wrapper.style.zIndex = '100001';
                    const box = document.createElement('div');
                    box.style.width = '360px';
                    box.style.padding = '18px';
                    box.style.background = '#fff';
                    box.style.borderRadius = '10px';
                    box.style.textAlign = 'center';
                    box.innerHTML = '<h3 style="margin-top:0;">Verify PayPal</h3><div id="paypal-button-container"></div><p style="font-size:12px;color:#666;margin-top:8px;">A temporary authorization (sandbox) will be requested and voided automatically.</p><button id="paypalCancelBtn" style="margin-top:10px;padding:8px 12px;border:none;background:#ccc;border-radius:6px;">Cancel</button>';
                    wrapper.appendChild(box);
                    document.body.appendChild(wrapper);
                    document.getElementById('paypalCancelBtn').addEventListener('click', cleanup);
                }

                // Render PayPal Buttons into container
                paypal.Buttons({
                    style: { layout: 'vertical', color: 'blue', shape: 'rect' },
                        createOrder: function(data, actions) {
                            // Use server to create an order (AUTHORIZE) and return orderID
                            // Use GET to simplify server acceptance
                            return fetch('auth-system/create_paypal_order.php', {
                                method: 'GET'
                            }).then(function(res){ return res.json(); }).then(function(data){
                                console.log('create_paypal_order response', data);
                                if (data && data.orderID) return data.orderID;
                                throw new Error(data.message || 'Could not create PayPal order');
                            }).catch(function(err){
                                console.error('Failed to create PayPal order', err);
                                showToast('❌ Could not create PayPal order: ' + (err.message || ''), 'error');
                                throw err;
                            });
                        },
                    onApprove: function(data, actions) {
                        // Authorize the order (returns authorization details)
                        return actions.order.authorize().then(async function(authData){
                                try {
                                    // Extract authorization id from response
                                    let authId = null;
                                    try {
                                        const pu = authData.purchase_units && authData.purchase_units[0];
                                        if (pu && pu.payments && pu.payments.authorizations && pu.payments.authorizations[0]) {
                                            authId = pu.payments.authorizations[0].id;
                                        }
                                    } catch(e) { /* ignore */ }

                                    if (!authId) {
                                        console.warn('Could not find authorization id in PayPal response', authData);
                                        showToast('❌ Could not locate PayPal authorization id', 'error');
                                        return cleanup();
                                    }

                                    // Send authorization id to server for verification
                                    const resp = await fetch('auth-system/verify_paypal_authorization.php', {
                                        method: 'POST',
                                        headers: { 'Content-Type': 'application/json' },
                                        body: JSON.stringify({ authorization_id: authId })
                                    });
                                    const j = await resp.json();
                                    if (j && j.success) {
                                        window.paypalVerified = true;
                                        showToast('✅ PayPal verified (server confirmed)', 'success');
                                        const paypalForm = document.getElementById('form-paypal');
                                        const btn = paypalForm ? paypalForm.querySelector('.verify-btn') : null;
                                        if (btn) { btn.textContent = 'Verified ✓'; btn.style.background = '#2e7d32'; }
                                    } else {
                                        console.error('PayPal server verification failed', j);
                                        showToast('❌ PayPal verification failed on server', 'error');
                                    }
                                    setTimeout(cleanup, 800);
                                } catch (err) {
                                    console.error('Authorization error', err);
                                    showToast('❌ PayPal authorization failed', 'error');
                                    cleanup();
                                }
                            }).catch(function(err){
                                console.error('Authorization error', err);
                                showToast('❌ PayPal authorization failed', 'error');
                                cleanup();
                            });
                    },
                    onError: function(err) {
                        console.error('PayPal Buttons error', err);
                        showToast('❌ PayPal error: ' + (err && err.message ? err.message : ''), 'error');
                    }
                }).render('#paypal-button-container');

                // Disable original verify button while PayPal modal is active
                const origBtn = document.querySelector('#form-paypal .verify-btn');
                if (origBtn) { origBtn.disabled = true; origBtn.style.opacity = '0.6'; }

                function cleanup() {
                    const el = document.getElementById('paypalVerifyModal');
                    if (el) el.remove();
                    if (origBtn) { origBtn.disabled = false; origBtn.style.opacity = '1'; }
                }
            }
        }

        // Bank verify: simple IBAN / numeric check placeholder
        function verifyBank() {
            const chk = document.querySelector('input[name="bank_transfer_confirm"]');
            if (!chk) return;
            if (!chk.checked) {
                showToast('❌ Please confirm bank transfer checkbox first', 'error');
                return;
            }
            showToast('✅ Bank transfer confirmation noted (client-side)', 'success');
            window.bankVerified = true;
            const bankForm = document.getElementById('form-bank_transfer');
            const btn = bankForm ? bankForm.querySelector('.verify-btn') : null;
            if (btn) { btn.textContent = 'Verified ✓'; btn.style.background = '#2e7d32'; }
        }

        // Add small verify buttons to PayPal and Bank forms
        (function addVerifyButtons(){
            const paypalForm = document.getElementById('form-paypal');
            if (paypalForm && !paypalForm.querySelector('.verify-btn')) {
                const btn = document.createElement('button');
                btn.type = 'button'; btn.className = 'verify-btn'; btn.textContent = 'Verify PayPal';
                btn.style.marginTop = '8px'; btn.style.padding='8px 12px'; btn.style.border='none'; btn.style.background='#1976d2'; btn.style.color='#fff'; btn.style.borderRadius='6px';
                btn.addEventListener('click', verifyPayPal);
                paypalForm.appendChild(btn);
            }

            const bankForm = document.getElementById('form-bank_transfer');
            if (bankForm && !bankForm.querySelector('.verify-btn')) {
                const btn = document.createElement('button');
                btn.type = 'button'; btn.className = 'verify-btn'; btn.textContent = 'Verify Transfer';
                btn.style.marginTop = '8px'; btn.style.padding='8px 12px'; btn.style.border='none'; btn.style.background='#1976d2'; btn.style.color='#fff'; btn.style.borderRadius='6px';
                btn.addEventListener('click', verifyBank);
                bankForm.appendChild(btn);
            }

            // Add Verify Card button for credit card form (if not present)
            const creditForm = document.getElementById('form-credit_card');
            if (creditForm && !creditForm.querySelector('.verify-card-btn')) {
                const vbtn = document.createElement('button');
                vbtn.type = 'button'; vbtn.className = 'verify-card-btn verify-btn'; vbtn.textContent = 'Verify Card';
                vbtn.style.marginTop = '8px'; vbtn.style.marginLeft = '8px'; vbtn.style.padding='8px 12px'; vbtn.style.border='none'; vbtn.style.background='#0b74de'; vbtn.style.color='#fff'; vbtn.style.borderRadius='6px';
                vbtn.addEventListener('click', verifyCard);
                creditForm.appendChild(vbtn);
            }
        })();

        // Verify card using Stripe SetupIntent (no charge) — marks window.paymentMethodVerified and stores payment_method id
        async function verifyCard() {
            if (!window.stripe || !window.cardElement) {
                showToast('Stripe not configured. Cannot verify card here.', 'error');
                return;
            }

            const name = (document.querySelector('input[name="card_holder"]')||{value:''}).value || (document.querySelector('input[name="first_name"]')||{value:''}).value;
            if (!name) {
                showToast('Please enter card holder name before verification', 'error');
                return;
            }

            try {
                const res = await fetch('auth-system/create_setup_intent.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({})
                });
                const data = await res.json();
                if (!data.success || !data.setup_intent) {
                    throw new Error(data.message || 'Could not create setup intent');
                }

                const clientSecret = data.setup_intent.client_secret;
                showToast('🔒 Confirming card for verification...', 'info');

                const result = await window.stripe.confirmCardSetup(clientSecret, {
                    payment_method: {
                        card: window.cardElement,
                        billing_details: { name: name }
                    }
                });

                if (result.error) {
                    throw new Error(result.error.message || 'Verification failed');
                }

                if (result.setupIntent && result.setupIntent.status === 'succeeded') {
                    // Send setup_intent id to server for verification
                    const setupId = result.setupIntent.id;
                    try {
                        const vresp = await fetch('auth-system/verify_setup_intent.php', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ setup_intent_id: setupId })
                        });
                        const vdata = await vresp.json();
                        if (vdata && vdata.success) {
                            const pm = result.setupIntent.payment_method;
                            window.verifiedPaymentMethodId = pm;
                            window.paymentMethodVerified = true;
                            showToast('✅ Card verified (server confirmed)', 'success');
                            const vbtn = document.querySelector('.verify-card-btn');
                            if (vbtn) { vbtn.textContent = 'Verified ✓'; vbtn.style.background = '#2e7d32'; }
                        } else {
                            throw new Error(vdata.message || 'Server verification failed');
                        }
                    } catch (err) {
                        console.error('Server verify error', err);
                        showToast('❌ Card verification failed on server: ' + (err.message||''), 'error');
                    }
                } else {
                    throw new Error('Verification did not complete');
                }
            } catch (err) {
                console.error('Verify card error', err);
                showToast('❌ ' + (err.message || 'Card verification failed'), 'error');
            }
        }

        /**
         * Validate payment method before form submission
         */
        function validatePaymentMethod() {
            const paymentMethod = document.querySelector('input[name="payment_method"]:checked').value;
            
            switch(paymentMethod) {
                case 'credit_card':
                    // Require client-side verification before final submit
                    if (!window.paymentMethodVerified) {
                        showToast('🔒 Please verify your card before placing the order', 'error');
                        return false;
                    }
                    return validateCardHolder(document.querySelector('input[name="card_holder"]')) &&
                           validateCardNumber(document.querySelector('input[name="card_number"]')) &&
                           validateCardExpiry(document.querySelector('input[name="card_expiry"]')) &&
                           validateCardCVV(document.querySelector('input[name="card_cvv"]'));
                
                case 'paypal':
                    if (!validatePayPalEmail(document.querySelector('input[name="paypal_email"]'))) return false;
                    if (!window.paypalVerified) {
                        showToast('🔒 Please verify your PayPal before placing the order', 'error');
                        return false;
                    }
                    return true;
                
                case 'bank_transfer':
                    const bankConfirm = document.querySelector('input[name="bank_transfer_confirm"]');
                    if (!bankConfirm.checked) {
                        showError(bankConfirm, document.getElementById('error-bank_transfer_confirm'), 
                                 'You must confirm to proceed with bank transfer');
                        return false;
                    }
                    clearError(bankConfirm, document.getElementById('error-bank_transfer_confirm'));
                    if (!window.bankVerified) {
                        showToast('🔒 Please verify your bank transfer before placing the order', 'error');
                        return false;
                    }
                    return true;
                
                case 'cod':
                    const codConfirm = document.querySelector('input[name="cod_confirm"]');
                    if (!codConfirm.checked) {
                        showError(codConfirm, document.getElementById('error-cod_confirm'), 
                                 'You must agree to the terms to proceed');
                        return false;
                    }
                    clearError(codConfirm, document.getElementById('error-cod_confirm'));
                    return true;
                
                case 'upi':
                    if (!window.upiPaymentVerified) {
                        showToast('💳 Please confirm your UPI payment before placing the order', 'error');
                        return false;
                    }
                    return true;
                
                default:
                    return false;
            }
        }

        /**
         * UPI Payment Functions - Complete Integration
         */
        let upiTransaction = {
            id: null,
            qrCodeUrl: null,
            upiString: null,
            amount: null
        };

        async function generateUPIQRCode() {
            try {
                const totalAmount = <?php echo $total; ?>;
                
                // Call backend API to generate QR code
                const response = await fetch('auth-system/upi-payment-api.php?action=generate_qr', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        amount: totalAmount
                    })
                });
                
                if (!response.ok) {
                    throw new Error('Failed to generate QR code');
                }
                
                const result = await response.json();
                
                if (!result.success) {
                    throw new Error(result.message);
                }
                
                // Store transaction data
                upiTransaction = {
                    id: result.data.transaction_id,
                    qrCodeUrl: result.data.qr_code_url,
                    upiString: result.data.upi_string,
                    amount: result.data.amount,
                    merchantUPI: result.data.merchant_upi,
                    transactionRef: result.data.transaction_ref
                };
                
                // Display QR code
                const qrImage = document.getElementById('upiQrCode');
                if (qrImage) {
                    qrImage.src = upiTransaction.qrCodeUrl;
                    qrImage.style.display = 'block';
                }
                
                console.log('✅ UPI QR Code generated successfully', upiTransaction);
                showToast('✅ QR Code generated! Ready to scan.', 'success');
                
            } catch (error) {
                console.error('Error generating QR code:', error);
                showToast('❌ Error generating QR code: ' + error.message, 'error');
            }
        }

        async function verifyUPIPayment(upiId) {
            try {
                if (!upiTransaction.id) {
                    throw new Error('Transaction not initialized');
                }
                
                // Call backend API to verify UPI ID
                const response = await fetch('auth-system/upi-payment-api.php?action=verify_upi', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        upi_id: upiId,
                        transaction_id: upiTransaction.id
                    })
                });
                
                if (!response.ok) {
                    throw new Error('Failed to verify UPI');
                }
                
                const result = await response.json();
                
                if (!result.success) {
                    throw new Error(result.message);
                }
                
                console.log('✅ UPI verified:', result.data);
                return true;
                
            } catch (error) {
                console.error('Error verifying UPI:', error);
                showToast('❌ Error verifying UPI: ' + error.message, 'error');
                return false;
            }
        }

        function initUPIPayment() {
            const upiIdInput = document.querySelector('input[name="upi_id"]');
            const upiPayBtn = document.getElementById('upiPayBtn');
            const upiManualBtn = document.getElementById('upiManualBtn');
            
            // Generate QR code when UPI form is shown
            generateUPIQRCode();
            
            // Handle "Open UPI App" button
            if (upiPayBtn) {
                upiPayBtn.addEventListener('click', async function(e) {
                    e.preventDefault();
                    const upiId = upiIdInput.value.trim();
                    
                    if (!upiId) {
                        showToast('⚠️ Please enter your UPI ID or scan the QR code', 'error');
                        return;
                    }
                    
                    // Validate UPI ID format
                    if (!/^[a-zA-Z0-9._-]+@[a-zA-Z]{3,}$/.test(upiId)) {
                        showToast('❌ Invalid UPI ID format. Use format: 9876543210@okhdfcbank', 'error');
                        return;
                    }
                    
                    // Verify UPI
                    showUPIStatus('processing');
                    const verified = await verifyUPIPayment(upiId);
                    
                    if (!verified) {
                        showUPIStatus('error');
                        return;
                    }
                    
                    // Open UPI deep link
                    const merchantName = 'Interior Design Store';
                    const upiLink = `upi://pay?pa=${upiId}&pn=${encodeURIComponent(merchantName)}&am=${upiTransaction.amount}&tn=Order%20Payment&tr=${upiTransaction.transactionRef}`;
                    
                    // Try to open UPI app
                    window.location.href = upiLink;
                    
                    // Show waiting status
                    showUPIStatus('waiting');
                    
                    // Set timeout for user to return from UPI app
                    setTimeout(() => {
                        showToast('⏳ Complete payment in your UPI app and return here', 'info');
                    }, 1000);
                });
            }
            
            // Handle "Confirm Payment Done" button
            if (upiManualBtn) {
                upiManualBtn.addEventListener('click', async function(e) {
                    e.preventDefault();
                    
                    if (!upiTransaction.id) {
                        showToast('❌ Transaction not initialized. Please refresh and try again.', 'error');
                        return;
                    }
                    
                    // Show processing status
                    showUPIStatus('processing');
                    
                    try {
                        // Verify payment with backend
                        const checkResponse = await fetch(`auth-system/upi-payment-api.php?action=check_payment_status&transaction_id=${upiTransaction.id}`, {
                            method: 'GET',
                            headers: {
                                'Content-Type': 'application/json'
                            }
                        });
                        
                        if (!checkResponse.ok) {
                            throw new Error('Failed to check payment status');
                        }
                        
                        const checkResult = await checkResponse.json();
                        
                        if (!checkResult.success) {
                            throw new Error(checkResult.message);
                        }
                        
                        const transaction = checkResult.data;
                        
                        if (transaction.status === 'verified') {
                            window.upiPaymentVerified = true;
                            window.upiTransactionId = upiTransaction.id;
                            showUPIStatus('success');
                            showToast('✅ UPI Payment confirmed! Ready to place order.', 'success');
                            console.log('✅ UPI payment verified:', transaction);
                        } else {
                            throw new Error('Payment not yet verified. Please try again.');
                        }
                        
                    } catch (error) {
                        console.error('Error confirming payment:', error);
                        showUPIStatus('error');
                        showToast('❌ Error confirming payment: ' + error.message, 'error');
                    }
                });
            }
            
            // UPI ID validation
            if (upiIdInput) {
                upiIdInput.addEventListener('blur', function() {
                    const value = this.value.trim();
                    const errorEl = document.getElementById('error-upi_id');
                    
                    if (value && !/^[a-zA-Z0-9._-]+@[a-zA-Z]{3,}$/.test(value)) {
                        showError(this, errorEl, 'Invalid UPI ID format (e.g., 9876543210@okhdfcbank)');
                    } else {
                        clearError(this, errorEl);
                    }
                });
            }
        }

        function showUPIStatus(status) {
            const statusDiv = document.getElementById('upiPaymentStatus');
            const statusIcon = document.getElementById('upiStatusIcon');
            const statusText = document.getElementById('upiStatusText');
            
            statusDiv.style.display = 'flex';
            statusDiv.className = 'upi-status';
            
            switch(status) {
                case 'waiting':
                    statusDiv.classList.add('waiting');
                    statusIcon.textContent = '⏳';
                    statusText.textContent = 'Waiting for payment... Complete payment in your UPI app.';
                    break;
                case 'processing':
                    statusDiv.classList.add('processing');
                    statusIcon.textContent = '⏳';
                    statusText.textContent = 'Verifying payment...';
                    break;
                case 'success':
                    statusDiv.classList.add('success');
                    statusIcon.textContent = '✅';
                    statusText.textContent = 'Payment received! Your order will be placed shortly.';
                    break;
                case 'error':
                    statusDiv.classList.add('error');
                    statusIcon.textContent = '❌';
                    statusText.textContent = 'Payment verification failed. Please try again.';
                    break;
                default:
                    statusDiv.style.display = 'none';
            }
        }

        // Initialize UPI when payment method is selected
        document.querySelectorAll('input[name="payment_method"]').forEach(radio => {
            radio.addEventListener('change', function() {
                if (this.value === 'upi') {
                    setTimeout(initUPIPayment, 300);
                }
            });
        });

        // Initialize if UPI is already checked
        if (document.querySelector('input[name="payment_method"][value="upi"]:checked')) {
            initUPIPayment();
        }

        /**
         * Handle form submission
         */
        document.getElementById('checkoutForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            // Validate payment method
            if (!validatePaymentMethod()) {
                showToast('❌ Please check your payment method details', 'error');
                return;
            }

            const form = this;
            const formData = new FormData(form);
            const loading = document.getElementById('loading');
            const submitBtn = form.querySelector('button[type="submit"]');

            submitBtn.disabled = true;
            loading.classList.add('active');

            try {
                const selectedMethod = document.querySelector('input[name="payment_method"]:checked').value;

                // Handle UPI payment separately
                if (selectedMethod === 'upi') {
                    if (!window.upiPaymentVerified || !window.upiTransactionId) {
                        throw new Error('UPI payment not verified');
                    }

                    // Process UPI payment and create order
                    const upiResponse = await fetch('auth-system/upi-payment-api.php?action=process_payment', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            transaction_id: window.upiTransactionId,
                            billing_address: {
                                first_name: formData.get('first_name'),
                                last_name: formData.get('last_name'),
                                email: formData.get('email'),
                                phone: formData.get('phone'),
                                country: formData.get('country'),
                                address: formData.get('address'),
                                city: formData.get('city'),
                                postcode: formData.get('postcode')
                            },
                            shipping_address: formData.get('ship_to_different') ? {
                                first_name: formData.get('shipping_first_name'),
                                last_name: formData.get('shipping_last_name'),
                                country: formData.get('shipping_country'),
                                address: formData.get('shipping_address'),
                                city: formData.get('shipping_city'),
                                postcode: formData.get('shipping_postcode')
                            } : null
                        })
                    });

                    const upiData = await upiResponse.json();

                    if (upiData.success && upiData.data.order_id) {
                        window.lastOrderId = upiData.data.order_id;
                        document.getElementById('modalOrderId').textContent = '#' + upiData.data.order_id;
                        document.getElementById('modalOrderTotal').textContent = 'Rs. ' + new Intl.NumberFormat('en-IN').format(Math.round(upiData.data.amount));
                        document.getElementById('confirmationModal').classList.add('active');
                        
                        showToast('✅ Order placed successfully!', 'success');
                        
                        setTimeout(function() {
                            window.location.href = 'order-confirmation.php?order_id=' + upiData.data.order_id;
                        }, 2000);
                        return;
                    } else {
                        throw new Error(upiData.message || 'Error processing UPI payment');
                    }
                }

                // If Stripe is configured and user chose card, use PaymentIntent flow
                if (selectedMethod === 'credit_card' && typeof stripe !== 'undefined' && stripe) {
                    // compute amount from #total text (strip non-digits)
                    let totalText = document.getElementById('total').textContent || '';
                    let totalNum = Number(totalText.replace(/[^0-9.-]+/g, '')) || 0;
                    // smallest currency unit
                    const amount = Math.round(totalNum * 100);

                    // Create PaymentIntent on server
                    const piResp = await fetch('auth-system/create_payment_intent.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ amount: amount, currency: 'usd' })
                    });
                    const piData = await piResp.json();
                    if (!piData.success || !piData.payment_intent) {
                        throw new Error(piData.message || 'Failed to create payment intent');
                    }

                    const clientSecret = piData.payment_intent.client_secret;

                    // Confirm card payment (handles 3DS and authentication)
                    const result = await stripe.confirmCardPayment(clientSecret, {
                        payment_method: {
                            card: cardElement,
                            billing_details: { name: formData.get('card_holder') || formData.get('first_name') }
                        }
                    });

                    if (result.error) {
                        throw new Error(result.error.message || 'Payment failed');
                    }

                    if (result.paymentIntent && result.paymentIntent.status === 'succeeded') {
                        // append payment_intent_id to payload and submit order
                        formData.set('payment_intent_id', result.paymentIntent.id);
                        const response = await fetch('auth-system/checkout-api.php?action=place_order', {
                            method: 'POST',
                            body: JSON.stringify(Object.fromEntries(formData))
                        });
                        const data = await response.json();
                        if (data.success && data.order_id) {
                            window.lastOrderId = data.order_id;
                            document.getElementById('modalOrderId').textContent = '#' + data.order_id;
                            document.getElementById('modalOrderTotal').textContent = 'Rs. ' + new Intl.NumberFormat('en-PK').format(Math.round(data.total));
                            document.getElementById('confirmationModal').classList.add('active');
                            showToast('✅ Payment successful and order placed', 'success');
                            setTimeout(function() { window.location.href = 'order-confirmation.php?order_id=' + data.order_id; }, 3000);
                        } else {
                            throw new Error(data.message || 'Order placement failed');
                        }
                    } else {
                        throw new Error('Payment not completed');
                    }

                    return;
                }

                // Fallback: existing flow for non-card methods or when Stripe not configured
                const response = await fetch('auth-system/checkout-api.php?action=place_order', {
                    method: 'POST',
                    body: JSON.stringify(Object.fromEntries(formData))
                });

                const data = await response.json();
                console.log('Response:', data);

                if (data.success && data.order_id) {
                    // Store order ID globally
                    window.lastOrderId = data.order_id;
                    
                    // Show confirmation modal
                    document.getElementById('modalOrderId').textContent = '#' + data.order_id;
                    document.getElementById('modalOrderTotal').textContent = 'Rs. ' + new Intl.NumberFormat('en-PK').format(Math.round(data.total));
                    document.getElementById('confirmationModal').classList.add('active');
                    
                    showToast('✅ Order placed successfully! Redirecting...', 'success');
                    
                    // Redirect to order confirmation page after 3 seconds
                    setTimeout(function() {
                        const redirectUrl = 'order-confirmation.php?order_id=' + data.order_id;
                        window.location.href = redirectUrl;
                    }, 3000);
                } else {
                    showToast('❌ ' + (data.message || 'Error placing order'), 'error');
                    console.error('Order placement failed:', data);
                }
            } catch (error) {
                console.error('Error:', error);
                showToast('❌ ' + (error.message || 'Error placing order'), 'error');
            } finally {
                submitBtn.disabled = false;
                loading.classList.remove('active');
            }
        });

        /**
         * Display toast notification
         */
        function showToast(message, type) {
            const toast = document.getElementById('toast');
            toast.textContent = message;
            toast.className = 'toast ' + type;
            toast.style.display = 'block';
            setTimeout(() => {
                toast.style.display = 'none';
            }, 4000);
        }

        /**
         * Navigate to orders page
         */
        function goToOrders() {
            if (window.lastOrderId) {
                window.location.href = 'order-confirmation.php?order_id=' + window.lastOrderId;
            } else {
                window.location.href = 'orders.php';
            }
        }

        /**
         * Continue shopping
         */
        function continueShopping() {
            window.location.href = 'shop.php';
        }
    </script>

    <?php include 'footer-section.html'; ?>
</body>
</html>
