<?php
/**
 * Checkout Payment Step 3
 * Converted from checkout-v1-payment.html
 * Final step of checkout - payment and order completion
 */

$pageTitle = 'Cartzilla | Finalizare Comandă - Plată';
$pageDescription = 'Cartzilla - Magazin Online E-Commerce';

// Initialize classes BEFORE header to allow redirects
require_once __DIR__ . '/includes/init.php';
$cart = new Cart();
$product = new Product();
$userObj = new User();
$order = new Order();
$auth = new Auth();
$b2b = new B2B();

// Get user ID and session ID
$userId = $auth->getUserId();
$sessionId = session_id();

// Check if cart is empty
$cartData = $cart->getOrCreateCart($userId, $sessionId);
$cartItems = $cart->getCartItems($cartData['id']);

if (empty($cartItems)) {
    header('Location: /cos');
    exit;
}

// Check if shipping address is set (from step 2)
$shippingAddress = $_SESSION['checkout_shipping_address'] ?? null;
$postcode = $_SESSION['checkout_postcode'] ?? '';

if (empty($shippingAddress) || empty($postcode)) {
    header('Location: /checkout/transport');
    exit;
}

// Get user B2B group for pricing
$b2bGroup = $userId ? $b2b->getUserB2BGroup($userId) : null;

// Calculate totals
$subtotal = 0;
$savings = 0;
$itemCount = 0;

foreach ($cartItems as $item) {
    $productData = $product->getProductById($item['product_id']);
    if ($productData) {
        $currentPrice = $product->getProductPrice($productData, $b2bGroup, $userId);
        $originalPrice = $productData['sale_price'] ?? $productData['price'];
        
        if ($originalPrice > $currentPrice) {
            $savings += ($originalPrice - $currentPrice) * $item['quantity'];
        }
        
        $subtotal += $currentPrice * $item['quantity'];
        $itemCount += $item['quantity'];
    }
}

// Calculate shipping cost
$freeShippingThreshold = 500;
$shippingCost = $subtotal >= $freeShippingThreshold ? 0 : 25;

// Tax (19% VAT for Romania)
$taxRate = 0.19;
$tax = $subtotal * $taxRate;

// Get user loyalty points
$userData = $userId ? $user->getUserById($userId) : null;
$availableLoyaltyPoints = $userData['loyalty_points'] ?? 0;
$loyaltyPointsValue = $availableLoyaltyPoints; // 1 point = 1 RON

// Handle form submission (BEFORE header to allow redirects)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $paymentMethod = $_POST['payment_method'] ?? 'cash_on_delivery';
    $couponCode = $_POST['coupon_code'] ?? '';
    $loyaltyPointsUsed = isset($_POST['use_loyalty_points']) ? min((int)$_POST['loyalty_points'], $availableLoyaltyPoints) : 0;
    $notes = $_POST['notes'] ?? '';
    $sameBillingAddress = isset($_POST['same_billing_address']) && $_POST['same_billing_address'] == '1';
    
    // Calculate discount from loyalty points
    $loyaltyDiscount = min($loyaltyPointsUsed, $subtotal); // Can't discount more than subtotal
    
    // Apply coupon if provided
    $couponDiscount = 0;
    if (!empty($couponCode)) {
        $coupon = $order->validateCoupon($couponCode, $subtotal);
        if ($coupon) {
            if ($coupon['type'] === 'percentage') {
                $couponDiscount = ($subtotal * $coupon['value']) / 100;
                if ($coupon['max_discount']) {
                    $couponDiscount = min($couponDiscount, $coupon['max_discount']);
                }
            } else {
                $couponDiscount = $coupon['value'];
            }
        }
    }
    
    $totalDiscount = $loyaltyDiscount + $couponDiscount;
    $finalTotal = $subtotal - $totalDiscount + $tax + $shippingCost;
    
    // Prepare order data
    $orderData = [
        'order_type' => 'physical',
        'payment_method' => $paymentMethod,
        'coupon_code' => !empty($couponCode) ? $couponCode : null,
        'loyalty_points_used' => $loyaltyPointsUsed,
        'shipping_cost' => $shippingCost,
        'notes' => $notes
    ];
    
    // Save addresses
    if ($userId) {
        // Save shipping address
        $shippingAddressId = $userObj->addAddress($userId, array_merge($shippingAddress, ['is_default' => 0]));
        
        // Save billing address (same or different)
        if ($sameBillingAddress) {
            $billingAddressId = $shippingAddressId;
        } else {
            $billingAddress = [
                'first_name' => $_POST['billing_first_name'] ?? $shippingAddress['first_name'],
                'last_name' => $_POST['billing_last_name'] ?? $shippingAddress['last_name'],
                'email' => $_POST['billing_email'] ?? $shippingAddress['email'],
                'phone' => $_POST['billing_phone'] ?? $shippingAddress['phone'],
                'city' => $_POST['billing_city'] ?? $shippingAddress['city'],
                'county' => $_POST['billing_county'] ?? $shippingAddress['county'],
                'postal_code' => $_POST['billing_postal_code'] ?? $shippingAddress['postal_code'],
                'address_line1' => $_POST['billing_address_line1'] ?? $shippingAddress['address_line1'],
                'address_line2' => $_POST['billing_address_line2'] ?? $shippingAddress['address_line2'],
                'country' => $_POST['billing_country'] ?? $shippingAddress['country'],
                'type' => 'billing',
                'is_default' => 0
            ];
            $billingAddressId = $userObj->addAddress($userId, $billingAddress);
        }
        
        $orderData['shipping_address_id'] = $shippingAddressId;
        $orderData['billing_address_id'] = $billingAddressId;
    }
    
    // Create order
    $result = $order->createOrder($cartData['id'], $userId, $orderData);
    
    if ($result['success']) {
        // Clear checkout session data
        unset($_SESSION['checkout_postcode']);
        unset($_SESSION['checkout_shipping_address']);
        
        // Redirect to thank you page
        header('Location: /checkout/multumim?order=' . urlencode($result['order_number']));
        exit;
    } else {
        $errorMessage = $result['message'] ?? 'Failed to create order. Please try again.';
    }
}

// Now include header (after all redirects and form processing are handled)
require_once __DIR__ . '/includes/header.php';

// Calculate final total for display
$estimatedTotal = $subtotal + $tax + $shippingCost;

// Get cart items for preview
$cartItemsPreview = array_slice($cartItems, 0, 3);

// Calculate loyalty points that will be earned
require_once __DIR__ . '/includes/Loyalty.php';
$loyalty = new Loyalty();
$pointsEarned = $loyalty->calculatePointsFromOrder($estimatedTotal);
?>

    <!-- Page content -->
    <main class="content-wrapper">
      <div class="container py-5">
        <div class="row pt-1 pt-sm-3 pt-lg-4 pb-2 pb-md-3 pb-lg-4 pb-xl-5">
          <div class="col-lg-8 col-xl-7 position-relative z-2 mb-5 mb-lg-0">
            <div class="accordion d-flex flex-column gap-5 pe-lg-4 pe-xl-0" id="checkout">

              <!-- Delivery info overview + Edit button -->
              <div class="accordion-item d-flex align-items-start border-0">
                <div class="d-flex align-items-center justify-content-center bg-body-secondary text-dark-emphasis rounded-circle flex-shrink-0" style="width: 2rem; height: 2rem; margin-top: -.125rem">
                  <i class="ci-check fs-base"></i>
                </div>
                <div class="w-100 ps-3 ps-md-4">
                  <div class="d-flex align-items-center">
                    <h2 class="accordion-header h5 mb-0 me-3" id="deliveryInfoHeading">
                      <span class="d-none d-lg-inline">Informații livrare</span>
                      <button type="button" class="accordion-button collapsed fs-5 d-lg-none py-1" data-bs-toggle="collapse" data-bs-target="#deliveryInfo" aria-expanded="false" aria-controls="deliveryInfo">
                        <span class="me-2">Informații livrare</span>
                      </button>
                    </h2>
                    <div class="nav ms-auto">
                      <a class="nav-link text-decoration-underline p-0" href="/checkout/livrare">Editează</a>
                    </div>
                  </div>
                  <div class="accordion-collapse collapse d-lg-block" id="deliveryInfo" aria-labelledby="deliveryInfoHeading" data-bs-parent="#checkout">
                    <div class="accordion-body p-0 pt-3 pt-md-4">
                      <h3 class="fs-sm mb-2">Cod poștal</h3>
                      <p class="fs-sm"><?php echo htmlspecialchars($postcode); ?></p>
                      <h3 class="fs-sm mb-2">Data estimată de livrare</h3>
                      <div class="d-flex align-items-center fs-sm">
                        <?php
                        $days = ['Monday' => 'Luni', 'Tuesday' => 'Marți', 'Wednesday' => 'Miercuri', 'Thursday' => 'Joi', 'Friday' => 'Vineri', 'Saturday' => 'Sâmbătă', 'Sunday' => 'Duminică'];
                        $dayName = $days[date('l', strtotime('+3 days'))] ?? date('l', strtotime('+3 days'));
                        echo $dayName . ', ' . date('j', strtotime('+3 days'));
                        ?>
                        <span class="opacity-40 mx-2">|</span>
                        09:00 - 17:00
                      </div>
                    </div>
                  </div>
                </div>
              </div>


              <!-- Shipping address overview + Edit button -->
              <div class="accordion-item d-flex align-items-start border-0">
                <div class="d-flex align-items-center justify-content-center bg-body-secondary text-dark-emphasis rounded-circle flex-shrink-0" style="width: 2rem; height: 2rem; margin-top: -.125rem">
                  <i class="ci-check fs-base"></i>
                </div>
                <div class="w-100 ps-3 ps-md-4">
                  <div class="d-flex align-items-center">
                    <h2 class="accordion-header h5 mb-0 me-3" id="shippingAddressHeading">
                      <span class="d-none d-lg-inline">Adresă livrare</span>
                      <button type="button" class="accordion-button collapsed fs-5 d-lg-none py-1" data-bs-toggle="collapse" data-bs-target="#shippingAddress" aria-expanded="false" aria-controls="shippingAddress">
                        <span class="me-2">Adresă livrare</span>
                      </button>
                    </h2>
                    <div class="nav ms-auto">
                      <a class="nav-link text-decoration-underline p-0" href="/checkout/transport">Editează</a>
                    </div>
                  </div>
                  <div class="accordion-collapse collapse d-lg-block" id="shippingAddress" aria-labelledby="shippingAddressHeading" data-bs-parent="#checkout">
                    <ul class="accordion-body list-unstyled fs-sm p-0 pt-3 pt-md-4 mb-0">
                      <li><?php echo htmlspecialchars($shippingAddress['first_name'] . ' ' . $shippingAddress['last_name']); ?></li>
                      <li><?php echo htmlspecialchars($shippingAddress['email']); ?></li>
                      <?php if (!empty($shippingAddress['phone'])): ?>
                      <li><?php echo htmlspecialchars($shippingAddress['phone']); ?></li>
                      <?php endif; ?>
                      <li><?php echo htmlspecialchars($shippingAddress['city'] . ', ' . $shippingAddress['county'] . ' ' . $shippingAddress['postal_code']); ?></li>
                      <li><?php echo htmlspecialchars($shippingAddress['address_line1']); ?></li>
                      <?php if (!empty($shippingAddress['address_line2'])): ?>
                      <li><?php echo htmlspecialchars($shippingAddress['address_line2']); ?></li>
                      <?php endif; ?>
                    </ul>
                  </div>
                </div>
              </div>


              <!-- Payment method -->
              <div class="d-flex align-items-start">
                <div class="d-flex align-items-center justify-content-center bg-primary text-white rounded-circle fs-sm fw-semibold lh-1 flex-shrink-0" style="width: 2rem; height: 2rem; margin-top: -.125rem">3</div>
                <div class="w-100 ps-3 ps-md-4">
                  <h2 class="h5 mb-0">Plată</h2>
                  
                  <?php if (isset($errorMessage)): ?>
                  <div class="alert alert-danger mt-3" role="alert">
                    <?php echo htmlspecialchars($errorMessage); ?>
                  </div>
                  <?php endif; ?>
                  
                  <form method="POST" id="paymentForm">
                    <div class="mb-4" id="paymentMethod" role="list">

                      <!-- Cash on delivery -->
                      <div class="mt-4">
                        <div class="form-check mb-0" role="listitem" data-bs-toggle="collapse" data-bs-target="#cash" aria-expanded="false" aria-controls="cash">
                          <label class="form-check-label w-100 text-dark-emphasis fw-semibold">
                            <input type="radio" class="form-check-input fs-base me-2 me-sm-3" name="payment_method" value="cash_on_delivery" checked>
                            Ramburs la livrare
                          </label>
                        </div>
                        <div class="collapse" id="cash" data-bs-parent="#paymentMethod">
                          <div class="d-sm-flex align-items-center pt-3 pt-sm-4 pb-2 ps-3 ms-2 ms-sm-3">
                            <span class="fs-sm me-3">Voi avea nevoie de rest de la:</span>
                            <div class="input-group mt-2 mt-sm-0" style="max-width: 150px">
                              <span class="input-group-text">
                                <i class="ci-dollar-sign"></i>
                              </span>
                              <input type="number" class="form-control" name="change_from" placeholder="Sumă" min="<?php echo $estimatedTotal; ?>" step="0.01">
                            </div>
                          </div>
                        </div>
                      </div>

                      <!-- Credit card -->
                      <div class="mt-4">
                        <div class="form-check mb-0" role="listitem" data-bs-toggle="collapse" data-bs-target="#card" aria-expanded="false" aria-controls="card">
                          <label class="form-check-label d-flex align-items-center text-dark-emphasis fw-semibold">
                            <input type="radio" class="form-check-input fs-base me-2 me-sm-3" name="payment_method" value="credit_card">
                            Card de credit sau debit
                            <span class="d-none d-sm-flex gap-2 ms-3">
                              <img src="assets/img/payment-methods/amex.svg" class="d-block bg-info rounded-1" width="36" alt="Amex">
                              <img src="assets/img/payment-methods/visa-light-mode.svg" class="d-none-dark" width="36" alt="Visa">
                              <img src="assets/img/payment-methods/visa-dark-mode.svg" class="d-none d-block-dark" width="36" alt="Visa">
                              <img src="assets/img/payment-methods/mastercard.svg" width="36" alt="Mastercard">
                              <img src="assets/img/payment-methods/maestro.svg" width="36" alt="Maestro">
                            </span>
                          </label>
                        </div>
                        <div class="collapse" id="card" data-bs-parent="#paymentMethod">
                          <div class="pt-4 pb-2 ps-3 ms-2 ms-sm-3">
                            <p class="fs-sm text-body-secondary mb-3">Plata cu cardul va fi procesată în siguranță prin gateway-ul nostru de plată.</p>
                            <div class="alert alert-info" role="alert">
                              <i class="ci-info me-2"></i>
                              În scopuri demo, plata cu cardul nu este complet implementată. Te rugăm să folosești "Ramburs la livrare" pentru testare.
                            </div>
                          </div>
                        </div>
                      </div>

                      <!-- PayPal -->
                      <div class="mt-4">
                        <div class="form-check mb-0" role="listitem" data-bs-toggle="collapse" data-bs-target="#paypal" aria-expanded="false" aria-controls="paypal">
                          <label class="form-check-label d-flex align-items-center text-dark-emphasis fw-semibold">
                            <input type="radio" class="form-check-input fs-base me-2 me-sm-3" name="payment_method" value="paypal">
                            PayPal
                            <img src="assets/img/payment-methods/paypal-icon.svg" class="ms-3" width="16" alt="PayPal">
                          </label>
                        </div>
                        <div class="collapse" id="paypal" data-bs-parent="#paymentMethod">
                          <div class="pt-4 pb-2 ps-3 ms-2 ms-sm-3">
                            <p class="fs-sm text-body-secondary">Vei fi redirecționat către PayPal pentru a finaliza plata.</p>
                          </div>
                        </div>
                      </div>

                      <!-- Google Pay -->
                      <div class="mt-4">
                        <div class="form-check mb-0" role="listitem" data-bs-toggle="collapse" data-bs-target="#googlepay" aria-expanded="false" aria-controls="googlepay">
                          <label class="form-check-label d-flex align-items-center text-dark-emphasis fw-semibold">
                            <input type="radio" class="form-check-input fs-base me-2 me-sm-3" name="payment_method" value="google_pay">
                            Google Pay
                            <img src="assets/img/payment-methods/google-icon.svg" class="ms-3" width="20" alt="Google Pay">
                          </label>
                        </div>
                        <div class="collapse" id="googlepay" data-bs-parent="#paymentMethod">
                          <div class="pt-4 pb-2 ps-3 ms-2 ms-sm-3">
                            <p class="fs-sm text-body-secondary">Vei fi redirecționat către Google Pay pentru a finaliza plata.</p>
                          </div>
                        </div>
                      </div>
                    </div>

                    <!-- Loyalty points (if user is logged in and has points) -->
                    <?php if ($userId && $availableLoyaltyPoints > 0): ?>
                    <div class="border rounded p-3 mb-4">
                      <div class="form-check mb-2">
                        <input type="checkbox" class="form-check-input" id="use_loyalty_points" name="use_loyalty_points" value="1" onchange="toggleLoyaltyPoints()">
                        <label for="use_loyalty_points" class="form-check-label">
                          Folosește puncte fidelitate (Disponibile: <strong><?php echo $availableLoyaltyPoints; ?></strong> puncte = <strong><?php echo number_format($loyaltyPointsValue, 2); ?> RON</strong>)
                        </label>
                      </div>
                      <div id="loyaltyPointsInput" style="display: none;">
                        <label for="loyalty_points" class="form-label fs-sm">Sumă de folosit (max <?php echo $availableLoyaltyPoints; ?> puncte):</label>
                        <input type="number" class="form-control" id="loyalty_points" name="loyalty_points" min="0" max="<?php echo $availableLoyaltyPoints; ?>" value="0" onchange="updateTotal()">
                      </div>
                    </div>
                    <?php endif; ?>

                    <!-- Add promo code -->
                    <div class="mb-4">
                      <div class="nav pb-3 mb-2 mb-sm-3">
                        <a class="nav-link animate-underline p-0" href="#!" onclick="document.getElementById('promoCodeSection').style.display = 'block'; this.style.display = 'none'; return false;">
                          <i class="ci-plus-circle fs-xl ms-a me-2"></i>
                          <span class="animate-target">Adaugă un cod promoțional sau un card cadou</span>
                        </a>
                      </div>
                      <div id="promoCodeSection" style="display: none;">
                        <div class="input-group">
                          <input type="text" class="form-control form-control-lg" name="coupon_code" placeholder="Introdu codul promoțional">
                          <button type="button" class="btn btn-lg btn-outline-secondary" onclick="validateCoupon()">Aplică</button>
                        </div>
                        <div id="couponMessage" class="mt-2"></div>
                      </div>
                    </div>

                    <!-- Additional comments -->
                    <textarea class="form-control form-control-lg mb-4" name="notes" rows="3" placeholder="Comentarii adiționale"></textarea>

                    <!-- Same billing address -->
                    <input type="hidden" name="same_billing_address" value="1" id="same_billing_address_hidden">

                    <div class="form-check mb-lg-4">
                      <input type="checkbox" class="form-check-input" id="accept-terms" required>
                      <label for="accept-terms" class="form-check-label nav align-items-center">
                        Accept
                        <a class="nav-link text-decoration-underline fw-normal ms-1 p-0" href="/terms-and-conditions">Termenii și Condițiile</a>
                      </label>
                    </div>

                    <!-- Pay button -->
                    <button type="submit" class="btn btn-lg btn-primary w-100" id="payButton">
                      Plătește <?php echo number_format($estimatedTotal, 2); ?> RON
                    </button>
                  </form>
                </div>
              </div>
            </div>
          </div>


          <!-- Order summary (sticky sidebar) -->
          <aside class="col-lg-4 offset-xl-1" style="margin-top: -100px">
            <div class="position-sticky top-0" style="padding-top: 100px">
              <div class="bg-body-tertiary rounded-5 p-4 mb-3">
                <div class="p-sm-2 p-lg-0 p-xl-2">
                  <div class="border-bottom pb-4 mb-4">
                    <div class="d-flex align-items-center justify-content-between mb-4">
                      <h5 class="mb-0">Rezumat comandă</h5>
                      <div class="nav">
                        <a class="nav-link text-decoration-underline p-0" href="/cos">Editează</a>
                      </div>
                    </div>
                    <a class="d-flex align-items-center gap-2 text-decoration-none" href="/cos">
                      <?php foreach ($cartItemsPreview as $previewItem): ?>
                      <?php
                      $previewProduct = $product->getProductById($previewItem['product_id']);
                      $previewImage = $previewProduct['image'] ?? 'assets/img/shop/electronics/thumbs/01.png';
                      if (!str_starts_with($previewImage, 'http') && !str_starts_with($previewImage, '/') && !str_starts_with($previewImage, 'assets/')) {
                          $previewImage = 'assets/img/shop/electronics/thumbs/' . $previewImage;
                      }
                      ?>
                      <div class="ratio ratio-1x1" style="max-width: 64px">
                        <img src="<?php echo htmlspecialchars($previewImage); ?>" class="d-block p-1" alt="<?php echo htmlspecialchars($previewItem['name']); ?>">
                      </div>
                      <?php endforeach; ?>
                      <?php if (count($cartItems) > 3): ?>
                      <div class="ratio ratio-1x1 bg-body-secondary rounded d-flex align-items-center justify-content-center" style="max-width: 64px">
                        <span class="fs-xs text-body-secondary">+<?php echo count($cartItems) - 3; ?></span>
                      </div>
                      <?php endif; ?>
                      <i class="ci-chevron-right text-body fs-xl p-0 ms-auto"></i>
                    </a>
                  </div>
                  <ul class="list-unstyled fs-sm gap-3 mb-0">
                    <li class="d-flex justify-content-between">
                      Subtotal (<?php echo $itemCount; ?> <?php echo $itemCount == 1 ? 'item' : 'items'; ?>):
                      <span class="text-dark-emphasis fw-medium"><?php echo number_format($subtotal, 2); ?> RON</span>
                    </li>
                    <?php if ($savings > 0): ?>
                    <li class="d-flex justify-content-between">
                      Economii:
                      <span class="text-danger fw-medium">-<?php echo number_format($savings, 2); ?> RON</span>
                    </li>
                    <?php endif; ?>
                    <li class="d-flex justify-content-between">
                      TVA (19%):
                      <span class="text-dark-emphasis fw-medium"><?php echo number_format($tax, 2); ?> RON</span>
                    </li>
                    <li class="d-flex justify-content-between">
                      Transport:
                      <span class="text-dark-emphasis fw-medium">
                        <?php if ($shippingCost == 0): ?>
                        <span class="text-success">Gratuit</span>
                        <?php else: ?>
                        <?php echo number_format($shippingCost, 2); ?> RON
                        <?php endif; ?>
                      </span>
                    </li>
                  </ul>
                  <div class="border-top pt-4 mt-4">
                    <div class="d-flex justify-content-between mb-3">
                      <span class="fs-sm">Total:</span>
                      <span class="h5 mb-0" id="finalTotal"><?php echo number_format($estimatedTotal, 2); ?> RON</span>
                    </div>
                  </div>
                </div>
              </div>
              <?php if ($pointsEarned > 0): ?>
              <div class="bg-body-tertiary rounded-5 p-4">
                <div class="d-flex align-items-center px-sm-2 px-lg-0 px-xl-2">
                  <svg class="text-warning flex-shrink-0" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"><path d="M1.333 9.667H7.5V16h-5c-.64 0-1.167-.527-1.167-1.167V9.667zm13.334 0v5.167c0 .64-.527 1.167-1.167 1.167h-5V9.667h6.167zM0 5.833V7.5c0 .64.527 1.167 1.167 1.167h.167H7.5v-1-3H1.167C.527 4.667 0 5.193 0 5.833zm14.833-1.166H8.5v3 1h6.167.167C15.473 8.667 16 8.14 16 7.5V5.833c0-.64-.527-1.167-1.167-1.167z"/><path d="M8 5.363a.5.5 0 0 1-.495-.573C7.752 3.123 9.054-.03 12.219-.03c1.807.001 2.447.977 2.447 1.813 0 1.486-2.069 3.58-6.667 3.58zM12.219.971c-2.388 0-3.295 2.27-3.595 3.377 1.884-.088 3.072-.565 3.756-.971.949-.563 1.287-1.193 1.287-1.595 0-.599-.747-.811-1.447-.811z"/><path d="M8.001 5.363c-4.598 0-6.667-2.094-6.667-3.58 0-.836.641-1.812 2.448-1.812 3.165 0 4.467 3.153 4.713 4.819a.5.5 0 0 1-.495.573zM3.782.971c-.7 0-1.448.213-1.448.812 0 .851 1.489 2.403 5.042 2.566C7.076 3.241 6.169.971 3.782.971z"/></svg>
                  <div class="text-dark-emphasis fs-sm ps-2 ms-1">Felicitări! Vei câștiga <span class="fw-semibold"><?php echo $pointsEarned; ?> bonusuri</span></div>
                </div>
              </div>
              <?php endif; ?>
            </div>
          </aside>
        </div>
      </div>
    </main>

<script>
function toggleLoyaltyPoints() {
    const checkbox = document.getElementById('use_loyalty_points');
    const input = document.getElementById('loyaltyPointsInput');
    if (checkbox.checked) {
        input.style.display = 'block';
    } else {
        input.style.display = 'none';
        document.getElementById('loyalty_points').value = 0;
        updateTotal();
    }
}

function updateTotal() {
    // This would update the total if loyalty points are used
    // For now, we'll just update the button text
    const loyaltyPoints = parseInt(document.getElementById('loyalty_points')?.value || 0);
    const baseTotal = <?php echo $estimatedTotal; ?>;
    const discount = Math.min(loyaltyPoints, baseTotal);
    const newTotal = baseTotal - discount;
    
    document.getElementById('finalTotal').textContent = newTotal.toFixed(2) + ' RON';
    document.getElementById('payButton').textContent = 'Pay ' + newTotal.toFixed(2) + ' RON';
}

function validateCoupon() {
    const code = document.querySelector('input[name="coupon_code"]').value;
    if (!code) return;
    
    fetch('/api/coupons.php?action=validate', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({code: code})
    })
    .then(r => r.json())
    .then(data => {
        const messageDiv = document.getElementById('couponMessage');
        if (data.success) {
            messageDiv.innerHTML = '<div class="alert alert-success">' + (data.message || 'Coupon applied successfully!') + '</div>';
        } else {
            messageDiv.innerHTML = '<div class="alert alert-danger">' + (data.message || 'Invalid coupon code') + '</div>';
        }
    });
}
</script>

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

