<?php
  require('includes/application_top1.php');

  // ========================================
  // AJAX HANDLER - Cerere Informații
  // ========================================
  if (isset($_POST['ajax_info_request']) && $_POST['ajax_info_request'] == '1') {
    // Curăță orice output produs de application_top1.php
    while (ob_get_level()) ob_end_clean();
    header('Content-Type: application/json; charset=utf-8');
    
    // Validare date
    $nume = isset($_POST['nume']) ? trim($_POST['nume']) : '';
    $prenume = isset($_POST['prenume']) ? trim($_POST['prenume']) : '';
    $firma = isset($_POST['firma']) ? trim($_POST['firma']) : '';
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $cantitate = isset($_POST['cantitate']) ? intval($_POST['cantitate']) : 0;
    $mentiuni = isset($_POST['mentiuni']) ? trim($_POST['mentiuni']) : '';
    $product_name = isset($_POST['product_name']) ? trim($_POST['product_name']) : '';
    $product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
    
    // Verificare câmpuri obligatorii
    if (empty($nume) || empty($prenume) || empty($email) || $cantitate < 1) {
      echo json_encode(['success' => false, 'message' => 'Vă rugăm completați toate câmpurile obligatorii.']);
      exit;
    }
    
    // Validare email
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      echo json_encode(['success' => false, 'message' => 'Adresa de email nu este validă.']);
      exit;
    }
    
    $catalogRoot = dirname(__FILE__) . '/';
    require_once $catalogRoot . 'scripts/mivarom_orocrm_import_lib.php';
    require_once DIR_WS_INCLUDES . 'functions/mivarom_integrations.php';

    $email_safe = filter_var($email, FILTER_SANITIZE_EMAIL);
    $full_name = trim($nume . ' ' . $prenume);
    $customer_id_value = isset($customer_id) ? (int) $customer_id : 0;
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $page_url = $scheme . '://' . ($_SERVER['HTTP_HOST'] ?? 'www.mivarom.ro') . ($_SERVER['REQUEST_URI'] ?? '/product_info.php');

    try {
      $result = mivarom_orocrm_create_post_order_case([
        'customer_id' => $customer_id_value,
        'email' => $email_safe,
        'name' => $full_name,
        'company' => $firma,
        'order_id' => 0,
        'product_id' => $product_id,
        'product_name' => $product_name,
        'quantity' => $cantitate,
        'case_type' => 'product_info_request',
        'details' => $mentiuni !== '' ? $mentiuni : 'Solicitare trimisa din pagina produsului prin butonul Cere informatii.',
        'page_url' => $page_url,
        'created_via' => 'product_info'
      ]);

      $emailSent = mivarom_send_product_info_case_customer_email([
        'case_id' => (int) ($result['case_id'] ?? 0),
        'customer_id' => $customer_id_value,
        'email' => $email_safe,
        'name' => $full_name,
        'company' => $firma,
        'product_id' => $product_id,
        'product_name' => $product_name,
        'quantity' => $cantitate,
        'case_type' => 'product_info_request',
        'details' => $mentiuni,
        'page_url' => $page_url
      ]);

      $log_entry = date('Y-m-d H:i:s') . " | " . $email_safe . " | " . $product_name . " | " . $cantitate . " buc | case #" . (int) ($result['case_id'] ?? 0) . "\n";
      @file_put_contents('info_requests.log', $log_entry, FILE_APPEND);

      echo json_encode([
        'success' => true,
        'message' => $emailSent
          ? 'Solicitarea a fost inregistrata. Am trimis pe email rezumatul cererii.'
          : 'Solicitarea a fost inregistrata cu succes.',
        'case_id' => (int) ($result['case_id'] ?? 0)
      ]);
    } catch (Throwable $e) {
      echo json_encode(['success' => false, 'message' => 'Nu am putut inregistra solicitarea. Va rugam sa incercati din nou.']);
    }
    exit;
  }
  // ========================================
  // END AJAX HANDLER
  // ========================================

  ob_start("callback");

  if (empty($lista_id)) {
    $lista_id = 1;
  }

  require(DIR_WS_LANGUAGES . $language . '/' . FILENAME_PRODUCT_INFO);

  // Un singur query pentru: existenta produs + header_tags + full product_info.
  // Inainte: 3 query-uri separate (COUNT pentru existenta, SELECT pentru tags, SELECT pentru info)
  // pe aceleasi tabele cu acelasi WHERE → 3 round-trips DB pe fiecare vizita pagina produs.
  $product_info_query = tep_db_query("select p.products_id, pd.products_name, pd.products_description, pd.title_tag, pd.desc_tag, pd.keywords_tag, p.products_model, p.stoc_erp, p.products_image, pd.products_url, p.products_price, p.products_tax_class_id, p.products_date_added, p.products_date_available, p.manufacturers_id, p.products_qty_blocks, p.products_quantity from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd where p.products_status = '1' and p.products_id = '" . (int)$_GET['products_id'] . "' and pd.products_id = p.products_id and pd.language_id = '" . (int)$languages_id . "'");
  $product_info = tep_db_fetch_array($product_info_query);
  $product_check = array('total' => $product_info ? 1 : 0);

  if ($product_info) {
    $header_tags = $product_info;
    $header_tags['products_name'] = trim($header_tags['products_name'] ?? '');
    $header_tags['title_tag'] = trim(strip_tags($header_tags['title_tag'] ?? ''));
    $header_tags['desc_tag'] = trim(strip_tags($header_tags['desc_tag'] ?? ''));
    $header_tags['keywords_tag'] = trim(strip_tags($header_tags['keywords_tag'] ?? ''));
    $header_tags['products_description'] = substr(preg_replace('/\s\s+/', ' ',(strip_tags($header_tags['products_description'] ?? ''))),0,1000);
    
    if (strlen($header_tags['title_tag']) < 2) {
      $header_tags['title_tag'] = $header_tags['products_name'];
    }
    
    if (isset($manufacturers['manufacturers_name']) && strlen($manufacturers['manufacturers_name']) > 1) $header_tags['title_tag'] .= ' ' . $manufacturers['manufacturers_name'] . ' ' . $header_tags['title_tag'];
    if (strlen($header_tags['desc_tag']) < 2) $header_tags['desc_tag'] = $header_tags['products_description'];
    if (strlen($header_tags['keywords_tag']) < 2) $header_tags['keywords_tag'] = $header_tags['products_name'];
    if (strpos($header_tags['products_name'], "Intex")) $header_tags['keywords_tag'] .= ", importator Intex, mouse, tastatura, casca, sistem, boxe, gamepad, bluetooth, laptop, utp, camera web, hub, suport, racire, sursa, atx, sursa atx, UPS";
  }
?>
<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html <?php echo HTML_PARAMS; ?>>
<head>
  <?php
// =========================================================================
// SCRIPT GENERARE CANONICAL URL
// =========================================================================
$canonical_url = '';

if (isset($_GET['products_id'])) {
    // Canonical pentru Produs
    $canonical_url = tep_href_link(FILENAME_PRODUCT_INFO, 'products_id=' . (int)$_GET['products_id'], 'NONSSL', false);
} elseif (isset($_GET['cPath'])) {
    // Canonical pentru Categorie
    $canonical_url = tep_href_link(FILENAME_DEFAULT, 'cPath=' . $_GET['cPath'], 'NONSSL', false);
} elseif (isset($_GET['manufacturers_id'])) {
    // Canonical pentru Producator
    $canonical_url = tep_href_link(FILENAME_DEFAULT, 'manufacturers_id=' . (int)$_GET['manufacturers_id'], 'NONSSL', false);
} else {
    // Canonical de fallback (ex: pentru prima pagina /index.php)
    $canonical_url = tep_href_link(basename($_SERVER['PHP_SELF']), '', 'NONSSL', false);
}

// Ne asiguram ca link-ul generat foloseste mereu HTTPS
$canonical_url = str_replace('http://', 'https://', $canonical_url);
?>
<link rel="canonical" href="<?php echo $canonical_url; ?>">
<script src="/javascripts/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="/js/jquery.effects.core.js"></script>
<script type="text/javascript" src="/js/jquery.effects.transfer.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>">
<title><?php echo $header_tags['title_tag']; ?></title>
<meta name="description" content="<?php echo $header_tags['desc_tag']; ?>">
<meta name="keywords" content="<?php echo $header_tags['keywords_tag']; ?>">
<meta name="robots" content="all" />
<meta name="rating" content="GENERAL" />
<meta name="resource-type" content="DOCUMENT" />
<meta name="distribution" content="GLOBAL" />
<META HTTP-EQUIV="CONTENT-LANGUAGE" CONTENT="RO">
<META NAME="charset" CONTENT="ISO-8859-2">
<META NAME="language" CONTENT="RO">
<base href="<?php echo (($request_type == 'SSL') ? HTTPS_SERVER : HTTP_SERVER) . DIR_WS_CATALOG; ?>">
<link rel="stylesheet" type="text/css" href="stylesheet.css">

<?php 
// Force cache refresh cu timestamp
echo '';
require(DIR_WS_INCLUDES . 'scripts_jquery1.php'); 
?>
<style type="text/css">
.ui-effects-transfer { border: 2px solid black; }

/* Modern Lightbox Styling */
.lightbox-overlay {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.9);
  z-index: 9999;
  cursor: pointer;
  animation: fadeIn 0.3s ease;
}

.lightbox-overlay.active {
  display: flex;
  align-items: center;
  justify-content: center;
}

.lightbox-content {
  max-width: 90%;
  max-height: 90%;
  cursor: default;
  animation: zoomIn 0.3s ease;
  position: relative;
}

.lightbox-content img {
  max-width: 100%;
  max-height: 90vh;
  width: auto;
  height: auto;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
  border-radius: 8px;
}

.lightbox-close {
  position: absolute;
  top: 20px;
  right: 20px;
  font-size: 40px;
  color: white;
  cursor: pointer;
  background: rgba(0, 0, 0, 0.5);
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  z-index: 10000;
}

.lightbox-close:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: rotate(90deg);
}

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

@keyframes zoomIn {
  from { 
    opacity: 0;
    transform: scale(0.8);
  }
  to { 
    opacity: 1;
    transform: scale(1);
  }
}
</style>
<script src="javascripts/search1.js" type="text/javascript"></script>

<script type="text/javascript">
function openLightbox(imageUrl) {
  var lightbox = document.getElementById('lightbox');
  var lightboxImage = document.getElementById('lightbox-image');
  if (lightbox && lightboxImage) {
    lightboxImage.src = imageUrl;
    lightbox.classList.add('active');
    document.body.style.overflow = 'hidden';
  }
  return false;
}

function closeLightbox() {
  var lightbox = document.getElementById('lightbox');
  if (lightbox) {
    lightbox.classList.remove('active');
    document.body.style.overflow = 'auto';
  }
}

function irOpenModal() {
  var m = document.getElementById('infoRequestModal');
  if (m) { m.classList.add('active'); document.body.style.overflow = 'hidden'; }
}

function irCloseModal() {
  var m = document.getElementById('infoRequestModal');
  if (m) {
    m.classList.remove('active');
    document.body.style.overflow = 'auto';
    var f = document.getElementById('infoRequestForm');
    if (f) f.reset();
    var msg = document.getElementById('formMessage');
    if (msg) msg.style.display = 'none';
  }
}

function irSubmit(btn) {
  var msg = document.getElementById('formMessage');
  var g = function(id) { var el = document.getElementById(id); return el ? el.value.trim() : ''; };
  var nume = g('ir_nume'), prenume = g('ir_prenume'), firma = g('ir_firma');
  var email = g('ir_email'), cantitate = g('ir_cantitate'), mentiuni = g('ir_mentiuni');
  var pname = g('ir_pname'), pid = g('ir_pid');

  if (!nume || !prenume || !email || !cantitate) {
    msg.style.cssText = 'display:block;background:#fee2e2;color:#991b1b;border:1px solid #fca5a5;padding:10px;border-radius:4px;';
    msg.textContent = 'Completati campurile obligatorii!';
    return;
  }

  btn.disabled = true;
  btn.textContent = 'Se trimite...';
  msg.style.display = 'none';

  var postData = 'ajax_info_request=1'
    + '&nume=' + encodeURIComponent(nume)
    + '&prenume=' + encodeURIComponent(prenume)
    + '&firma=' + encodeURIComponent(firma)
    + '&email=' + encodeURIComponent(email)
    + '&cantitate=' + encodeURIComponent(cantitate)
    + '&mentiuni=' + encodeURIComponent(mentiuni)
    + '&product_name=' + encodeURIComponent(pname)
    + '&product_id=' + encodeURIComponent(pid);

  var xhr = new XMLHttpRequest();
  xhr.open('POST', window.location.href, true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.onreadystatechange = function() {
    if (xhr.readyState !== 4) return;
    btn.disabled = false;
    btn.textContent = 'Trimite';
    msg.style.display = 'block';
    try {
      var m2 = xhr.responseText.match(/\{"success"[^}]*\}/);
      var data = m2 ? JSON.parse(m2[0]) : null;
      if (data && data.success) {
        msg.style.cssText = 'display:block;background:#d1fae5;color:#065f46;border:1px solid #6ee7b7;padding:10px;border-radius:4px;';
        msg.textContent = data.message || 'Trimis cu succes!';
        setTimeout(irCloseModal, 2000);
      } else {
        msg.style.cssText = 'display:block;background:#fee2e2;color:#991b1b;border:1px solid #fca5a5;padding:10px;border-radius:4px;';
        msg.textContent = (data && data.message) ? data.message : 'Eroare server!';
      }
    } catch(e) {
      msg.style.cssText = 'display:block;background:#fee2e2;color:#991b1b;border:1px solid #fca5a5;padding:10px;border-radius:4px;';
      msg.textContent = 'Eroare: ' + e.message;
    }
  };
  xhr.send(postData);
}

document.addEventListener('keydown', function(e) {
  if (e.key === 'Escape' || e.keyCode === 27) { closeLightbox(); irCloseModal(); }
});
/* ========================================
   AJAX ADD TO CART (Pagina Produs)
   ======================================== */
$(document).ready(function() {
    $('#cart_quantity').on('submit', function(e) {
        e.preventDefault(); 

        var $form = $(this);
        var $btn = $('#button_submit');
        var originalText = $btn.text();
        var originalBg = $btn.css("background-color");
        
        /* Gasim imaginea produsului pentru Fly */
        var $productImg = $('a[onclick^="openLightbox"] img').first();
        
        /* 1. Efectul de Fly */
        if ($productImg.length) {
var targetCart = (window.innerWidth <= 768) ? ".mobile-cart" : "#ajax_cart";
var options = { to: targetCart, className: "ui-effects-transfer" };
            $productImg.effect("transfer", options, 300);
        }

        /* 2. Feedback pe buton */
        $btn.text("...").prop("disabled", true);

        /* 3. Trimitem datele catre fisierul tau dedicat pt a salva produsul in sesiune */
        $.ajax({
            url: "ajax_add_cart.php",
            data: $form.serializeArray(),
            type: "POST",
            success: function() {
                /* 4. Extragem doar cosul reinnoit de pe pagina curenta */
             var currentUrl = window.location.href;
var separator = currentUrl.indexOf("?") !== -1 ? "&" : "?";
var timestamp = new Date().getTime();

/* 1. Actualizeaza cosul de desktop */
$("#ajax_cart").load(currentUrl + separator + "t=" + timestamp + " #ajax_cart > *", function() {
    $("#ajax_cart").stop(true, true).fadeOut(100).fadeIn(100);
    
    /* Resetare buton (acelasi cod pe care il ai deja) */
    $btn.text("Adăugat!").css("background-color", "#059669");
    setTimeout(function() {
        $btn.text(originalText).css("background-color", originalBg).prop("disabled", false);
    }, 1500);
});

/* 2. Actualizeaza numarul de pe cosul de mobil (daca exista in pagina) */
if ($(".mobile-cart").length) {
    $(".mobile-cart").load(currentUrl + separator + "t=" + timestamp + " .mobile-cart > *", function() {
        $(".mobile-cart").stop(true, true).fadeOut(100).fadeIn(100);
    });
}
            }
        });
    });
});
</script>

</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0">
<?php require(DIR_WS_INCLUDES . 'header.php'); ?>

<div class="container">
  <div class="main-layout">
    <aside class="column-left">
      <?php require(DIR_WS_INCLUDES . 'column_left.php'); ?>
    </aside>
    
    <main class="column-center">
      <?php
      echo tep_draw_form('cart_quantity', tep_href_link('product_info.php', tep_get_all_get_params(array('action')) . 'action=add_product', 'SSL'),'post','id="cart_quantity"');
      
      if ($product_check['total'] < 1) {
      ?>
        <div class="infoBox" style="padding: 20px; text-align: center;">
          <p class="main"><?php echo TEXT_PRODUCT_NOT_FOUND; ?></p>
          <div style="margin-top: 20px;">
            <a href="<?php echo tep_href_link(FILENAME_DEFAULT); ?>">
              <?php echo tep_image_button('button_continue.gif', IMAGE_BUTTON_CONTINUE); ?>
            </a>
          </div>
        </div>
      <?php
      } else {
        // $product_info este deja incarcat la inceputul paginii (query unificat) — nu repetam.

        // ERP: data aproximativa intrare in stoc (comanda tip 58 fara receptie tip 27 dupa)
        // Query SQL Server REMOTE — ~400ms roundtrip. Cache APCu 30 min per produs (data nu se schimba mai des).
        $erp_data_livrarii = null;
        if ($product_info && $product_info['products_quantity'] < 0) {
            $erp_apcu_key = 'osc_erp_livrare_' . DB_DATABASE . '_' . (int)$_GET['products_id'];
            $erp_cached = function_exists('apcu_fetch') ? apcu_fetch($erp_apcu_key, $erp_apcu_ok) : false;
            if ($erp_cached !== false) {
                $erp_data_livrarii = $erp_cached === '' ? null : $erp_cached;
            } else {
                try {
                    require_once __DIR__ . '/refa/includes/erp_ssrv.php';
                    $erp_conn = erp_ssrv();
                    $pid_str  = strval((int)$_GET['products_id']);
                    $sql_erp  = "SELECT TOP 1
                                     CONVERT(varchar(10), h.DataLivrarii, 23) AS data_livrarii
                                 FROM C_D_Note_Contabile d
                                 JOIN C_H_Note_Contabile h ON h.H_Id = d.H_Id
                                 WHERE d.Cod = ?
                                   AND h.Tip_Document_Id = 58
                                   AND d.Cantitate > 1
                                   AND h.DataLivrarii IS NOT NULL
                                   AND h.DataLivrarii > GETDATE()
                                   AND NOT EXISTS (
                                       SELECT 1
                                       FROM C_D_Note_Contabile d2
                                       JOIN C_H_Note_Contabile h2 ON h2.H_Id = d2.H_Id
                                       WHERE d2.Cod = d.Cod
                                         AND h2.Tip_Document_Id = 27
                                         AND h2.Data > h.Data
                                   )
                                 ORDER BY h.Data DESC";
                    $stmt_erp = sqlsrv_query($erp_conn, $sql_erp, [[$pid_str]]);
                    if ($stmt_erp) {
                        $row_erp = sqlsrv_fetch_array($stmt_erp, SQLSRV_FETCH_ASSOC);
                        if ($row_erp && !empty($row_erp['data_livrarii'])) {
                            $erp_data_livrarii = $row_erp['data_livrarii'];
                        }
                        sqlsrv_free_stmt($stmt_erp);
                    }
                    // Cache si rezultate "nimic gasit" (ca string gol) ca sa nu re-interogam ERP-ul.
                    if (function_exists('apcu_store')) {
                        apcu_store($erp_apcu_key, $erp_data_livrarii ?? '', 1800);
                    }
                } catch (Exception $e) {
                    // nu stricam pagina daca ERP nu e accesibil
                    // Cache scurt (60s) pentru retry rapid daca ERP-ul revine.
                    if (function_exists('apcu_store')) apcu_store($erp_apcu_key, '', 60);
                }
            }
        }

        // Counter products_viewed se update-aza dupa ce raspunsul a plecat la client (fastcgi_finish_request)
        // → user-ul nu mai asteapta lock-ul pe row-ul DB. Daca functia nu exista (CLI), update-ul se face inline.
        $_pid_viewed = (int)$_GET['products_id'];
        $_lang_viewed = (int)$languages_id;
        register_shutdown_function(function() use ($_pid_viewed, $_lang_viewed) {
          if (function_exists('fastcgi_finish_request')) fastcgi_finish_request();
          tep_db_query("update " . TABLE_PRODUCTS_DESCRIPTION . " set products_viewed = products_viewed+1 where products_id = '" . $_pid_viewed . "' and language_id = '" . $_lang_viewed . "'");
        });

        $pf->loadProduct((int)$_GET['products_id'], (int)$languages_id);
        $products_price = $pf->getPriceString();

        if (tep_not_null($product_info['products_model'])) {
          $products_name = $product_info['products_name'] . '<br><span class="smallText">[' . $product_info['products_model'] . ']</span>';
        } else {
          $products_name = $product_info['products_name'];
        }

        // =========================================================================
        // SCRIPT JSON-LD SCHEMA.ORG PENTRU RICH SNIPPETS IN GOOGLE
        // =========================================================================
        $schema_price = round(tep_add_tax($product_info['products_price'], tep_get_tax_rate($product_info['products_tax_class_id'])), 2);
        $schema_availability = ($product_info['stoc_erp'] > 0) ? 'https://schema.org/InStock' : 'https://schema.org/OutOfStock';
        $schema_url = (($request_type == 'SSL') ? HTTPS_SERVER : HTTP_SERVER) . DIR_WS_CATALOG . 'product_info.php?products_id=' . (int)$product_info['products_id'];
        $schema_img = (($request_type == 'SSL') ? HTTPS_SERVER : HTTP_SERVER) . DIR_WS_CATALOG . DIR_WS_IMAGES . $product_info['products_image'];
        $schema_desc = trim(substr(strip_tags($product_info['products_description'] ?? ''), 0, 300));
        // Daca produsul nu are deloc descriere in baza de date, folosim numele produsului ca descriere
        if (empty($schema_desc)) {
            $schema_desc = $product_info['products_name'];
        }
        $schema_sku = $product_info['products_id'];
        ?>
        <script type="application/ld+json">
        {
          "@context": "https://schema.org/",
          "@type": "Product",
          "name": "<?php echo htmlspecialchars($product_info['products_name'], ENT_QUOTES); ?>",
          "image": "<?php echo $schema_img; ?>",
          "description": "<?php echo htmlspecialchars($schema_desc, ENT_QUOTES); ?>",
          "sku": "<?php echo htmlspecialchars($schema_sku, ENT_QUOTES); ?>",
          "priceValidUntil": "<?php echo date('Y-m-d', strtotime('+1 day')); ?>",
          "brand": {
            "@type": "Brand",
            "name": "Mivarom"
          },
          "offers": {
            "@type": "Offer",
            "url": "<?php echo $schema_url; ?>",
            "priceCurrency": "RON",
            "price": "<?php echo $schema_price; ?>",
            "availability": "<?php echo $schema_availability; ?>",
            "itemCondition": "https://schema.org/NewCondition",
            "hasMerchantReturnPolicy": {
              "@type": "MerchantReturnPolicy",
              "applicableCountry": "RO",
              "returnPolicyCategory": "https://schema.org/MerchantReturnFiniteReturnWindow",
              "merchantReturnDays": 14,
              "returnMethod": "https://schema.org/ReturnByMail",
              "returnFees": "https://schema.org/FreeReturn"
            },
            "shippingDetails": {
              "@type": "OfferShippingDetails",
              "shippingRate": {
                "@type": "MonetaryAmount",
                "value": "0",
                "currency": "RON"
              },
              "shippingDestination": {
                "@type": "DefinedRegion",
                "addressCountry": "RO"
              },
              "deliveryTime": {
                "@type": "ShippingDeliveryTime",
                "handlingTime": {
                  "@type": "QuantitativeValue",
                  "minValue": 1,
                  "maxValue": 2,
                  "unitCode": "DAY"
                },
                "transitTime": {
                  "@type": "QuantitativeValue",
                  "minValue": 1,
                  "maxValue": 3,
                  "unitCode": "DAY"
                }
              },
              "orderMinimum": {
                "@type": "MonetaryAmount",
                "value": "500",
                "currency": "RON"
              }
            }
          }
        }
        </script>
       
        <table width="100%" cellpadding="10" cellspacing="0" border="0" style="margin-bottom: 20px; border: none;">
          
          <tr>
            <td width="75%" valign="top" style="padding: 15px; border: none;">
              <h1 class="pageHeading" style="margin: 0 0 20px 0; font-size: 22px; line-height: 1.3; color: #1e3a8a; font-weight: 700;">
                <?php echo $products_name; ?>
              </h1>
              
              <div id="price-wrapper" style="display: flex; justify-content: flex-start; width: 100%; margin: 0; padding: 0;">
                <div style="display: inline-block; text-align: left;">
                  <?php echo $products_price; ?>
                </div>
              </div>
              
              <script>
              // Forțează aliniere stânga pentru toate tabelele din price wrapper
              (function() {
                var wrapper = document.getElementById('price-wrapper');
                if (wrapper) {
                  var tables = wrapper.getElementsByTagName('table');
                  for (var i = 0; i < tables.length; i++) {
                    tables[i].style.marginLeft = '0';
                    tables[i].style.marginRight = 'auto';
                    tables[i].style.float = 'none';
                  }
                }
              })();
              </script>
            </td>
            
            <td width="25%" valign="top" style="padding: 15px; text-align: center; border: none;">
              <?php if (tep_not_null($product_info['products_image'])) {
                // Genereaza imagesmall daca nu exista
                $pinfo_src = $_SERVER['DOCUMENT_ROOT'].'/images/'.$product_info['products_image'];
                $pinfo_dst = $_SERVER['DOCUMENT_ROOT'].'/images/imagesmall/'.$product_info['products_image'];
                if (file_exists($pinfo_src) && !file_exists($pinfo_dst)) {
                  $pim = open_image($pinfo_src);
                  if ($pim !== false) {
                    $piw = imagesx($pim); $pih = imagesy($pim);
                    $psh = 120;
                    $psw = ($pih > 0) ? (int)round($psh * $piw / $pih) : $psh;
                    if ($psw < 1) $psw = $psh;
                    $pres = imagecreatetruecolor($psw, $psh);
                    imagecopyresampled($pres, $pim, 0, 0, 0, 0, $psw, $psh, $piw, $pih);
                    imagejpeg($pres, $pinfo_dst, 92);
                    imagedestroy($pres); imagedestroy($pim);
                  }
                }
              ?>
                <a href="#" onclick="openLightbox('<?php echo DIR_WS_IMAGES . $product_info['products_image']; ?>'); return false;" title="<?php echo $product_info['products_name']; ?>" style="cursor: zoom-in;">
                  <?php
                  // Am adaugat loading="lazy" in style-ul imaginii pentru o incarcare mult mai rapida
                  echo tep_image(DIR_WS_IMAGES .'imagesmall/'. $product_info['products_image'], $product_info['products_name'], '', '', 'loading="lazy" style="display: inline-block; width: auto; max-width: 100%; height: auto; max-height: 120px; vertical-align: middle; margin-left: auto; margin-right: auto; border-radius: 6px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); display: block; margin: 0 auto; transition: transform 0.2s;" onmouseover="this.style.transform=\'scale(1.05)\'" onmouseout="this.style.transform=\'scale(1)\'"');
                  ?>
                </a>
                <div style="margin-top: 8px; font-size: 11px; color: #6b7280;">
                  Mareste poza
                </div>
              <?php } ?>
            </td>
          </tr>
          
          <tr>
            <td colspan="2" valign="top" style="padding: 15px; border: none;">
              <?php if (tep_not_null($product_info['products_description'])) { ?>
                <div style="line-height: 1.6; color: #374151;">
                  <?php echo stripslashes($product_info['products_description']); ?>
                </div>
              <?php } ?>
              <?php if ($erp_data_livrarii): ?>
                <p style="margin-top: 10px;"><b>Data aproximativa de intrare in stoc: <?php echo htmlspecialchars($erp_data_livrarii); ?></b></p>
              <?php endif; ?>
            </td>
          </tr>
        </table>
        
        <div class="product-separator" style="margin: 20px 0; border-top: 1px solid #e5e7eb;"></div>
        
        <?php
          // Cache APCu (1h): daca tabelul products_attributes nu are randuri pentru acest produs,
          // skipam toate cele 1+N queries de mai jos. Mivarom: 0/10696 produse au atribute.
          $attr_apcu_key = 'osc_has_attr_' . DB_DATABASE . '_' . (int)$_GET['products_id'] . '_' . (int)$languages_id;
          $has_attributes = function_exists('apcu_fetch') ? apcu_fetch($attr_apcu_key, $attr_apcu_ok) : false;
          if ($has_attributes === false) {
            // EXISTS cu LIMIT 1 e mai rapid decat COUNT(*) (se opreste la primul match).
            $exists_query = tep_db_query("select 1 from " . TABLE_PRODUCTS_OPTIONS . " popt, " . TABLE_PRODUCTS_ATTRIBUTES . " patrib where patrib.products_id='" . (int)$_GET['products_id'] . "' and patrib.options_id = popt.products_options_id and popt.language_id = '" . (int)$languages_id . "' limit 1");
            $has_attributes = tep_db_num_rows($exists_query) > 0 ? 1 : 0;
            if (function_exists('apcu_store')) apcu_store($attr_apcu_key, $has_attributes, 3600);
          }

          if ($has_attributes) {
        ?>
            <div class="product-options-box" style="margin-bottom: 20px; padding: 15px; background: #f9fafb; border-radius: 6px;">
              <h3 style="margin: 0 0 15px 0; font-size: 16px; color: #1e3a8a;"><?php echo TEXT_PRODUCT_OPTIONS; ?></h3>
              <?php
              $products_options_name_query = tep_db_query("select distinct popt.products_options_id, popt.products_options_name from " . TABLE_PRODUCTS_OPTIONS . " popt, " . TABLE_PRODUCTS_ATTRIBUTES . " patrib where patrib.products_id='" . (int)$_GET['products_id'] . "' and patrib.options_id = popt.products_options_id and popt.language_id = '" . (int)$languages_id . "' order by popt.products_options_name");
              while ($products_options_name = tep_db_fetch_array($products_options_name_query)) {
                $products_options_array = array();
                $products_options_query = tep_db_query("select pov.products_options_values_id, pov.products_options_values_name, pa.options_values_price, pa.price_prefix from " . TABLE_PRODUCTS_ATTRIBUTES . " pa, " . TABLE_PRODUCTS_OPTIONS_VALUES . " pov where pa.products_id = '" . (int)$_GET['products_id'] . "' and pa.options_id = '" . (int)$products_options_name['products_options_id'] . "' and pa.options_values_id = pov.products_options_values_id and pov.language_id = '" . (int)$languages_id . "'");
                while ($products_options = tep_db_fetch_array($products_options_query)) {
                  $products_options_array[] = array('id' => $products_options['products_options_values_id'], 'text' => $products_options['products_options_values_name']);
                  if ($products_options['options_values_price'] != '0') {
                    $products_options_array[sizeof($products_options_array)-1]['text'] .= ' (' . $products_options['price_prefix'] . $currencies->display_price($products_options['options_values_price'], tep_get_tax_rate($product_info['products_tax_class_id'])) .') ';
                  }
                }
                if (isset($cart->contents[$_GET['products_id']]['attributes'][$products_options_name['products_options_id']])) {
                  $selected_attribute = $cart->contents[$_GET['products_id']]['attributes'][$products_options_name['products_options_id']];
                } else {
                  $selected_attribute = false;
                }
              ?>
                <div style="margin-bottom: 10px;">
                  <label style="display: inline-block; width: 150px; font-weight: 600;"><?php echo $products_options_name['products_options_name'] . ':'; ?></label>
                  <?php echo tep_draw_pull_down_menu('id[' . $products_options_name['products_options_id'] . ']', $products_options_array, $selected_attribute, 'style="padding: 6px 10px; border: 1px solid #d1d5db; border-radius: 4px;"'); ?>
                </div>
              <?php } ?>
            </div>
        <?php } ?>
        
        <?php if (isset($reviews['count']) && $reviews['count'] > 0) { ?>
            <div style="margin-bottom: 15px; padding: 10px; background: #eff6ff; border-radius: 4px;">
              <span style="color: #1e3a8a; font-weight: 600;"><?php echo TEXT_CURRENT_REVIEWS . ' ' . $reviews['count']; ?></span>
            </div>
        <?php } ?>
        
        <?php if (tep_not_null($product_info['products_url'])) { ?>
            <div style="margin-bottom: 15px;">
              <?php echo sprintf(TEXT_MORE_INFORMATION, tep_href_link(FILENAME_REDIRECT, 'action=url&goto=' . urlencode($product_info['products_url']), 'SSL', true, false)); ?>
            </div>
        <?php } ?>
        
        <?php if ($product_info['products_date_available'] > date('Y-m-d H:i:s')) { ?>
            <div style="margin-bottom: 15px; color: #dc2626;">
              <?php echo sprintf(TEXT_DATE_AVAILABLE, tep_date_long($product_info['products_date_available'])); ?>
            </div>
        <?php } ?>
        
        <div style="padding: 20px; background: #f9fafb; border-radius: 6px; border: 2px solid #2563eb;">
            <?php
            if($product_info['products_quantity'] < 0) {
              echo '<div style="display: flex; align-items: center; gap: 15px; justify-content: flex-end; flex-wrap: wrap;">';
              echo '<button type="button" onclick="(function(){var m=document.getElementById(\'infoRequestModal\');if(m){m.classList.add(\'active\');document.body.style.overflow=\'hidden\';}})();" style="padding: 10px 30px; background: #059669; color: white; border: none; border-radius: 4px; font-weight: 700; font-size: 14px; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.opacity=\'0.9\'" onmouseout="this.style.opacity=\'1\'">Cere informatii</button>';
              echo '<span style="display: inline-block; padding: 10px 20px; background: #9ca3af; color: white; border-radius: 4px; font-weight: 600;">' . IMAGE_BUTTON_SOLD_OUT . '</span>';
              echo '</div>';
  echo "<script>
if (typeof gtag === 'function') {
  gtag('event','lipsa_stoc_vizualizare',{
    event_category:'Lipsa stoc',
    event_label: ".json_encode($product_info['products_name']).",
    value: ".(round(tep_add_tax($product_info['products_price'],tep_get_tax_rate(1)),2)*100)."
  });
}
</script>";            } else {
            ?>
              <div style="display: flex; align-items: center; gap: 15px; flex-wrap: wrap; justify-content: flex-end;">
                <div>
                  <button type="button" onclick="(function(){var m=document.getElementById('infoRequestModal');if(m){m.classList.add('active');document.body.style.overflow='hidden';}})();" style="padding: 10px 30px; background: #059669; color: white; border: none; border-radius: 4px; font-weight: 700; font-size: 14px; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.opacity='0.9'" onmouseout="this.style.opacity='1'">
                    Cere informatii
                  </button>
                </div>
                
                <div>
                  <label style="font-weight: 600; color: #374151;">
                    <?php echo TEXT_ENTER_QUANTITY . ' (min. ' . ceil(0.5/tep_add_tax($product_info['products_price'],tep_get_tax_rate(1))). " buc):"; ?>
                  </label>
                </div>
                
                <div>
                  <?php echo tep_draw_input_field('cart_quantity', $pf->adjustQty(1), 'style="width: 80px; padding: 8px 12px; border: 1px solid #d1d5db; border-radius: 4px; text-align: center; font-weight: 600;"'); ?>
                </div>
                
                <div>
                  <?php echo tep_draw_hidden_field('products_id', $product_info['products_id']); ?>
                  <button type="submit" style="padding: 10px 30px; background: #2563eb; color: white; border: none; border-radius: 4px; font-weight: 700; font-size: 14px; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.opacity='0.9'" onmouseout="this.style.opacity='1'" id="button_submit">
                    Cumpara
                  </button>
                </div>
              </div>
            <?php } ?>
        </div>
        
        <div style="margin-top: 30px;">
            <?php
            $listaid = $lista_id;
            if ((USE_CACHE == 'true') && empty($SID)) {
              echo tep_cache_also_purchased(3600);
            } else {
              include(DIR_WS_MODULES . FILENAME_ALSO_PURCHASED_PRODUCTS);
            }
            ?>
        </div>
          
      <?php } ?>
      </form>
    </main>
    
    <aside class="column-right">
      <?php require(DIR_WS_INCLUDES . 'column_right.php'); ?>
    </aside>
    
  </div>
</div>

<div id="lightbox" class="lightbox-overlay" onclick="closeLightbox()">
  <span class="lightbox-close" onclick="closeLightbox()">&times;</span>
  <div class="lightbox-content" onclick="event.stopPropagation()">
    <img id="lightbox-image" src="" alt="">
  </div>
</div>

<div id="infoRequestModal" class="info-modal" onclick="this.classList.remove('active');document.body.style.overflow='auto';document.getElementById('infoRequestForm').reset();document.getElementById('formMessage').style.display='none';">
  <div class="info-modal-content" onclick="event.stopPropagation();">
    <span class="info-modal-close" onclick="document.getElementById('infoRequestModal').classList.remove('active');document.body.style.overflow='auto';document.getElementById('infoRequestForm').reset();document.getElementById('formMessage').style.display='none';">&times;</span>
    
    <h2 style="margin: 0 0 20px 0; color: #1e3a8a; font-size: 24px;">Cere Informații</h2>
    <p style="margin: 0 0 20px 0; color: #6b7280; font-size: 14px;">
      Produs: <strong><?php echo $product_info['products_name'] ?? ''; ?></strong>
    </p>

    <form id="infoRequestForm">
      <input type="hidden" name="ajax_info_request" value="1">
      <input type="hidden" id="ir_pname" name="product_name" value="<?php echo htmlspecialchars($product_info['products_name'] ?? ''); ?>">
      <input type="hidden" id="ir_pid" name="product_id" value="<?php echo $product_info['products_id'] ?? ''; ?>">
      
      <div class="form-row">
        <div class="form-group">
          <label>Nume <span style="color: #dc2626;">*</span></label>
          <input type="text" id="ir_nume" name="nume" placeholder="Nume">
        </div>
        
        <div class="form-group">
          <label>Prenume <span style="color: #dc2626;">*</span></label>
          <input type="text" id="ir_prenume" name="prenume" placeholder="Prenume">
        </div>
      </div>
      
      <div class="form-group">
        <label>Firma</label>
        <input type="text" id="ir_firma" name="firma" placeholder="Nume firmă (opțional)">
      </div>
      
      <div class="form-group">
        <label>Adresa de email <span style="color: #dc2626;">*</span></label>
        <input type="email" id="ir_email" name="email" placeholder="exemplu@email.com">
      </div>
      
      <div class="form-group">
        <label>Cantitate necesară <span style="color: #dc2626;">*</span></label>
        <input type="number" id="ir_cantitate" name="cantitate" min="1" value="1" placeholder="Cantitate">
      </div>
      
      <div class="form-group">
        <label>Mențiuni</label>
        <textarea id="ir_mentiuni" name="mentiuni" rows="4" placeholder="Detalii suplimentare sau întrebări..."></textarea>
      </div>
      
      <div id="formMessage" style="margin-bottom: 15px; padding: 10px; border-radius: 4px; display: none;"></div>
      
      <div style="text-align: right; margin-top: 20px;">
        <button type="button" onclick="document.getElementById('infoRequestModal').classList.remove('active');document.body.style.overflow='auto';document.getElementById('infoRequestForm').reset();document.getElementById('formMessage').style.display='none';" style="padding: 10px 30px; background: #9ca3af; color: white; border: none; border-radius: 4px; font-weight: 600; cursor: pointer; margin-right: 10px;">
          Anulează
        </button>
        <button type="button" id="ir_submit_btn" onclick="irSubmit(this);" style="padding: 10px 30px; background: #2563eb; color: white; border: none; border-radius: 4px; font-weight: 600; cursor: pointer;">
          Trimite
        </button>
      </div>
    </form>
  </div>
</div>

<style>
/* Modal Styles */
.info-modal {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  z-index: 10000;
  overflow-y: auto;
  animation: fadeIn 0.3s ease;
}

.info-modal.active {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.info-modal-content {
  background: white;
  border-radius: 8px;
  padding: 30px;
  max-width: 600px;
  width: 100%;
  max-height: 90vh;
  overflow-y: auto;
  position: relative;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  animation: slideUp 0.3s ease;
}

.info-modal-close {
  position: absolute;
  top: 15px;
  right: 20px;
  font-size: 32px;
  color: #6b7280;
  cursor: pointer;
  line-height: 1;
  transition: color 0.2s;
}

.info-modal-close:hover {
  color: #1e3a8a;
}

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

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 600;
  color: #374151;
  font-size: 14px;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 14px;
  font-family: inherit;
  transition: border-color 0.2s;
  box-sizing: border-box;
}

.form-group input:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #2563eb;
  box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
}

.form-group textarea {
  resize: vertical;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@media (max-width: 640px) {
  .form-row {
    grid-template-columns: 1fr;
  }
  
  .info-modal-content {
    padding: 20px;
  }
}
</style>

<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
<br>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
