<?php
/**
 * Product Details Page
 * Converted from shop-product-details-electronics.html
 * Displays detailed product information
 */

$pageTitle = 'Cartzilla | Magazin Electronice - Detalii Produs';
$pageDescription = 'Cartzilla - Magazin Online E-Commerce';

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

// Get product slug from URL (set by router)
$slug = $_GET['product_slug'] ?? null;

if (!$slug) {
    header('Location: /catalog');
    exit;
}

// Get product by slug
$productData = $product->getProductBySlug($slug);

if (!$productData) {
    header('HTTP/1.0 404 Not Found');
    require_once __DIR__ . '/404-electronics.php';
    exit;
}

// Now include header (after all redirects are handled)
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/product-card-helper.php';

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

// Get product price (with B2B discount if applicable)
$price = $product->getProductPrice($productData, $b2bGroup);
$hasSale = !empty($productData['sale_price']) && $productData['sale_price'] < $productData['price'];
$discountPercent = 0;
if ($hasSale) {
    $discountPercent = round((($productData['price'] - $productData['sale_price']) / $productData['price']) * 100);
}

// Get product image
$image = $productData['image'] ?? 'assets/img/shop/electronics/01.png';
if (!str_starts_with($image, 'http') && !str_starts_with($image, '/') && !str_starts_with($image, 'assets/')) {
    $image = 'assets/img/shop/electronics/' . $image;
}

// Get reviews count and average rating
$db = Database::getInstance();
$reviewsData = $db->fetchOne(
    "SELECT COUNT(*) as count, AVG(rating) as avg_rating FROM reviews WHERE product_id = ? AND is_approved = 1",
    [$productData['id']]
);
$reviewCount = $reviewsData['count'] ?? 0;
$avgRating = round($reviewsData['avg_rating'] ?? 0, 1);

// Generate stars HTML
$starsHtml = '';
for ($i = 1; $i <= 5; $i++) {
    if ($i <= floor($avgRating)) {
        $starsHtml .= '<i class="ci-star-filled text-warning"></i>';
    } elseif ($i == ceil($avgRating) && $avgRating != floor($avgRating)) {
        $starsHtml .= '<i class="ci-star-half text-warning"></i>';
    } else {
        $starsHtml .= '<i class="ci-star text-body-tertiary opacity-75"></i>';
    }
}

// Get related products (same category, excluding current product)
$relatedProducts = $product->getProducts([
    'category_id' => $productData['category_id'],
    'page' => 1,
    'per_page' => 8
]);
$relatedProducts = array_filter($relatedProducts, function($p) use ($productData) {
    return $p['id'] != $productData['id'];
});
$relatedProducts = array_slice($relatedProducts, 0, 4);

// Parse description for specs (if stored in description field)
// For now, we'll use the description as-is, but you can parse it if needed
$description = $productData['description'] ?? '';

$pageTitle = htmlspecialchars($productData['name']) . ' | Cartzilla';
?>

    <!-- Page content -->
    <main class="content-wrapper">

      <!-- Breadcrumb -->
      <nav class="container pt-3 my-3 my-md-4" aria-label="breadcrumb">
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="/">Acasă</a></li>
          <li class="breadcrumb-item"><a href="/catalog">Magazin</a></li>
          <?php if ($productData['category_name']): ?>
          <li class="breadcrumb-item"><a href="/catalog/<?php echo htmlspecialchars($productData['category_slug']); ?>"><?php echo htmlspecialchars($productData['category_name']); ?></a></li>
          <?php endif; ?>
          <li class="breadcrumb-item active" aria-current="page"><?php echo htmlspecialchars($productData['name']); ?></li>
        </ol>
      </nav>


      <!-- Page title -->
      <h1 class="h3 container mb-4"><?php echo htmlspecialchars($productData['name']); ?></h1>


      <!-- Nav links -->
      <section class="container position-relative z-2 pb-4 pb-md-5 mb-2 mb-md-0">
        <div class="border-bottom">
          <ul class="nav nav-underline flex-nowrap gap-4">
            <li class="nav-item me-sm-2">
              <a class="nav-link" href="/produs/<?php echo htmlspecialchars($productData['slug']); ?>">Informații generale</a>
            </li>
            <li class="nav-item me-sm-2">
              <a class="nav-link pe-none active" href="#!">Detalii produs</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="/produs/<?php echo htmlspecialchars($productData['slug']); ?>/recenzii">Recenzii (<?php echo $reviewCount; ?>)</a>
            </li>
          </ul>
        </div>
      </section>


      <!-- Product details + Sticky sidebar -->
      <section class="container pb-5 mb-2 mb-md-3 mb-lg-4 mb-xl-5">
        <div class="row">

          <!-- Sticky product preview -->
          <aside class="col-md-5 col-xl-4 offset-xl-1 order-md-2 mb-5 mb-md-0" id="scrollPastPoint" style="margin-top: -100px">
            <div class="position-sticky top-0 ps-md-3 ps-lg-4 ps-xl-0" style="padding-top: 100px">
              <div class="border rounded p-3 p-lg-4">
                <div class="d-flex align-items-center mb-3">
                  <div class="ratio ratio-1x1 flex-shrink-0" style="width: 110px">
                    <img src="<?php echo htmlspecialchars($image); ?>" width="110" alt="<?php echo htmlspecialchars($productData['name']); ?>">
                  </div>
                  <div class="w-100 min-w-0 ps-2 ps-sm-3">
                    <?php if ($reviewCount > 0): ?>
                    <div class="d-flex align-items-center gap-2 mb-2">
                      <div class="d-flex gap-1 fs-xs">
                        <?php echo $starsHtml; ?>
                      </div>
                      <span class="text-body-tertiary fs-xs"><?php echo $reviewCount; ?></span>
                    </div>
                    <?php endif; ?>
                    <h4 class="fs-sm fw-medium mb-2"><?php echo htmlspecialchars($productData['name']); ?></h4>
                    <div class="h5 mb-0">
                      <?php echo number_format($price, 2); ?> RON
                      <?php if ($hasSale && $price == $productData['sale_price']): ?>
                      <del class="text-body-tertiary fs-sm fw-normal"><?php echo number_format($productData['price'], 2); ?> RON</del>
                      <?php endif; ?>
                    </div>
                  </div>
                </div>
                <div class="d-flex gap-2 gap-lg-3">
                  <button type="button" class="btn btn-primary w-100 animate-slide-end add-to-cart" data-product-id="<?php echo $productData['id']; ?>">
                    <i class="ci-shopping-cart fs-base animate-target ms-n1 me-2"></i>
                    Adaugă în coș
                  </button>
                  <button type="button" class="btn btn-icon btn-secondary animate-pulse add-to-wishlist" data-product-id="<?php echo $productData['id']; ?>" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-custom-class="tooltip-sm" data-bs-title="Adaugă la favorite" aria-label="Adaugă la favorite">
                    <i class="ci-heart fs-base animate-target"></i>
                  </button>
                  <button type="button" class="btn btn-icon btn-secondary animate-rotate" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-custom-class="tooltip-sm" data-bs-title="Compare" aria-label="Compare">
                    <i class="ci-refresh-cw fs-base animate-target"></i>
                  </button>
                </div>
                <?php if ($productData['stock_quantity'] <= 0): ?>
                <div class="alert alert-warning mt-3 mb-0" role="alert">
                  <i class="ci-alert-circle me-2"></i>Stoc epuizat
                </div>
                <?php elseif ($productData['stock_quantity'] < 10): ?>
                <div class="alert alert-info mt-3 mb-0" role="alert">
                  <i class="ci-info me-2"></i>Doar <?php echo $productData['stock_quantity']; ?> rămase în stoc
                </div>
                <?php endif; ?>
              </div>
            </div>
          </aside>


          <!-- Sticky product preview + Add to cart CTA (Mobile) -->
          <section class="sticky-product-banner sticky-top d-md-none start-0 ms-n4" data-sticky-element>
            <div class="sticky-product-banner-inner start-0 pt-5">
              <div class="vw-100 bg-body border-bottom border-light border-opacity-10 shadow pt-4 pb-2">
                <div class="container d-flex align-items-center">
                  <div class="d-flex align-items-center min-w-0 ms-n2 me-3">
                    <div class="ratio ratio-1x1 flex-shrink-0" style="width: 50px">
                      <img src="<?php echo htmlspecialchars($image); ?>" alt="<?php echo htmlspecialchars($productData['name']); ?>">
                    </div>
                    <div class="w-100 min-w-0 ps-2">
                      <h4 class="fs-sm fw-medium text-truncate mb-1"><?php echo htmlspecialchars($productData['name']); ?></h4>
                      <div class="h6 mb-0"><?php echo number_format($price, 2); ?> RON</div>
                    </div>
                  </div>
                  <div class="d-flex gap-2 ms-auto">
                    <button type="button" class="btn btn-icon btn-secondary animate-pulse add-to-wishlist" data-product-id="<?php echo $productData['id']; ?>" aria-label="Add to Wishlist">
                      <i class="ci-heart fs-base animate-target"></i>
                    </button>
                    <button type="button" class="btn btn-primary animate-slide-end d-none d-sm-inline-flex add-to-cart" data-product-id="<?php echo $productData['id']; ?>">
                      <i class="ci-shopping-cart fs-base animate-target ms-n1 me-2"></i>
                      Add to cart
                    </button>
                    <button type="button" class="btn btn-icon btn-primary animate-slide-end d-sm-none add-to-cart" data-product-id="<?php echo $productData['id']; ?>" aria-label="Add to Cart">
                      <i class="ci-shopping-cart fs-lg animate-target"></i>
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </section>


          <!-- Product details -->
          <div class="col-md-7 order-md-1">
            <h2 class="h3 pb-2 pb-md-3">Detalii produs</h2>
            
            <?php if (!empty($description)): ?>
            <div class="mb-4">
              <?php echo nl2br(htmlspecialchars($description)); ?>
            </div>
            <?php endif; ?>
            
            <?php if (!empty($productData['short_description'])): ?>
            <div class="mb-4">
              <p class="text-body-secondary"><?php echo htmlspecialchars($productData['short_description']); ?></p>
            </div>
            <?php endif; ?>
            
            <h3 class="h6">Informații generale</h3>
            <ul class="list-unstyled d-flex flex-column gap-3 fs-sm pb-3 m-0 mb-2 mb-sm-3">
              <?php if (!empty($productData['sku'])): ?>
              <li class="d-flex align-items-center position-relative pe-4">
                <span>SKU:</span>
                <span class="d-block flex-grow-1 border-bottom border-dashed px-1 mt-2 mx-2"></span>
                <span class="text-dark-emphasis fw-medium text-end"><?php echo htmlspecialchars($productData['sku']); ?></span>
              </li>
              <?php endif; ?>
              <?php if (!empty($productData['category_name'])): ?>
              <li class="d-flex align-items-center position-relative pe-4">
                <span>Category:</span>
                <span class="d-block flex-grow-1 border-bottom border-dashed px-1 mt-2 mx-2"></span>
                <span class="text-dark-emphasis fw-medium text-end"><?php echo htmlspecialchars($productData['category_name']); ?></span>
              </li>
              <?php endif; ?>
              <?php if (!empty($productData['supplier_name'])): ?>
              <li class="d-flex align-items-center position-relative pe-4">
                <span>Supplier:</span>
                <span class="d-block flex-grow-1 border-bottom border-dashed px-1 mt-2 mx-2"></span>
                <span class="text-dark-emphasis fw-medium text-end"><?php echo htmlspecialchars($productData['supplier_name']); ?></span>
              </li>
              <?php endif; ?>
              <li class="d-flex align-items-center position-relative pe-4">
                <span>Stoc:</span>
                <span class="d-block flex-grow-1 border-bottom border-dashed px-1 mt-2 mx-2"></span>
                <span class="text-dark-emphasis fw-medium text-end"><?php echo $productData['stock_quantity'] > 0 ? $productData['stock_quantity'] . ' disponibile' : 'Stoc epuizat'; ?></span>
              </li>
              <li class="d-flex align-items-center position-relative pe-4">
                <span>Preț:</span>
                <span class="d-block flex-grow-1 border-bottom border-dashed px-1 mt-2 mx-2"></span>
                <span class="text-dark-emphasis fw-medium text-end">
                  <?php echo number_format($price, 2); ?> RON
                  <?php if ($hasSale && $price == $productData['sale_price']): ?>
                  <del class="text-body-tertiary fs-xs fw-normal"><?php echo number_format($productData['price'], 2); ?> RON</del>
                  <?php endif; ?>
                </span>
              </li>
            </ul>
            
            <div class="alert d-flex alert-info mb-2 mb-sm-3" role="alert">
              <i class="ci-info fs-lg pe-1 me-2" style="margin-top: .125rem"></i>
              <div class="fs-sm">Specificațiile produsului și echipamentele pot fi modificate fără notificare prealabilă.</div>
            </div>
            <div class="pt-3">
              <h3 class="h6">Ai întrebări?</h3>
              <a class="btn btn-sm btn-primary" href="/contact">Contactează-ne</a>
            </div>
          </div>
        </div>
      </section>


      <!-- Viewed products (Carousel) -->
      <?php if (!empty($relatedProducts)): ?>
      <section class="container pb-4 pb-md-5 mb-2 mb-sm-0 mb-lg-2 mb-xl-4">
        <h2 class="h3 border-bottom pb-4 mb-0">Produse similare</h2>

        <!-- Product carousel -->
        <div class="position-relative mx-md-1">

          <!-- External slider prev/next buttons visible on screens > 500px wide (sm breakpoint) -->
          <button type="button" class="viewed-prev btn btn-prev btn-icon btn-outline-secondary bg-body rounded-circle animate-slide-start position-absolute top-50 start-0 z-2 translate-middle-y ms-n1 d-none d-sm-inline-flex" aria-label="Prev">
            <i class="ci-chevron-left fs-lg animate-target"></i>
          </button>
          <button type="button" class="viewed-next btn btn-next btn-icon btn-outline-secondary bg-body rounded-circle animate-slide-end position-absolute top-50 end-0 z-2 translate-middle-y me-n1 d-none d-sm-inline-flex" aria-label="Next">
            <i class="ci-chevron-right fs-lg animate-target"></i>
          </button>

          <!-- Slider -->
          <div class="swiper py-4 px-sm-3" data-swiper='{
            "slidesPerView": 2,
            "spaceBetween": 24,
            "loop": true,
            "navigation": {
              "prevEl": ".viewed-prev",
              "nextEl": ".viewed-next"
            },
            "breakpoints": {
              "768": {
                "slidesPerView": 3
              },
              "992": {
                "slidesPerView": 4
              }
            }
          }'>
            <div class="swiper-wrapper">

              <?php foreach ($relatedProducts as $relatedProduct): ?>
              <div class="swiper-slide">
                <?php echo renderProductCard($relatedProduct, $b2bGroup); ?>
              </div>
              <?php endforeach; ?>

            </div>
          </div>
        </div>
      </section>
      <?php endif; ?>

    </main>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Add to cart functionality
    document.querySelectorAll('.add-to-cart').forEach(btn => {
        btn.addEventListener('click', function() {
            const productId = this.getAttribute('data-product-id');
            fetch('/api/cart.php?action=add', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({product_id: productId, quantity: 1})
            })
            .then(r => {
                if (!r.ok) {
                    throw new Error('HTTP error! status: ' + r.status);
                }
                return r.json();
            })
            .then(data => {
                if (data.success) {
                    // Update cart offcanvas dynamically
                    if (typeof refreshCartOffcanvas === 'function') {
                        refreshCartOffcanvas();
                    } else {
                        // Fallback: reload if function doesn't exist
                        location.reload();
                    }
                } else {
                    console.error('Cart API Error:', data);
                }
            })
            .catch(err => {
                console.error('Error:', err);
                showAlertModal('Eroare', 'A apărut o eroare: ' + err.message, 'error');
            });
        });
    });
    
    // Add to wishlist functionality
    document.querySelectorAll('.add-to-wishlist').forEach(btn => {
        btn.addEventListener('click', function() {
            const productId = this.getAttribute('data-product-id');
            fetch('/api/wishlist.php?action=add', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({product_id: productId})
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    showAlertModal('Succes', 'Produs adăugat la favorite!', 'success');
                } else {
                    showAlertModal('Atenție', data.message || 'Te rugăm să te autentifici pentru a adăuga la favorite', 'warning');
                }
            })
            .catch(err => {
                console.error('Error:', err);
                showAlertModal('Eroare', 'A apărut o eroare. Te rugăm să încerci din nou.', 'error');
            });
        });
    });
});
</script>

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

