<?php
/**
 * Account Wishlist Page
 * Converted from account-wishlist.html
 * Displays user's wishlist items
 */

$pageTitle = 'Cartzilla | Cont - Lista de Dorințe';
$pageDescription = 'Cartzilla - Magazin Online E-Commerce';

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

// Check if user is logged in
if (!$auth->isLoggedIn()) {
    header('Location: /cont/login?redirect=' . urlencode($_SERVER['REQUEST_URI']));
    exit;
}

$userId = $auth->getUserId();
$userData = $userObj->getUserById($userId);

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

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

// Get wishlist items
$wishlistItems = $db->fetchAll(
    "SELECT w.*, p.name, p.slug, p.image, p.price, p.sale_price, p.stock_quantity, p.id as product_id
     FROM wishlist w
     INNER JOIN products p ON w.product_id = p.id
     WHERE w.user_id = ? AND p.is_active = 1
     ORDER BY w.created_at DESC",
    [$userId]
);

// Handle remove action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'remove') {
    $productId = intval($_POST['product_id'] ?? 0);
    if ($productId) {
        $db->execute(
            "DELETE FROM wishlist WHERE user_id = ? AND product_id = ?",
            [$userId, $productId]
        );
        header('Location: /cont/wishlist');
        exit;
    }
}

// Handle add to cart action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_to_cart') {
    $productId = intval($_POST['product_id'] ?? 0);
    if ($productId) {
        $cart = new Cart();
        $sessionId = session_id();
        $cartData = $cart->getOrCreateCart($userId, $sessionId);
        $cart->addToCart($cartData['id'], $productId, 1);
        header('Location: /cont/wishlist');
        exit;
    }
}
?>

    <!-- Page content -->
    <main class="content-wrapper">
      <div class="container py-5 mt-n2 mt-sm-0">
        <div class="row pt-md-2 pt-lg-3 pb-sm-2 pb-md-3 pb-lg-4 pb-xl-5">

          <!-- Sidebar navigation -->
          <aside class="col-lg-3">
            <div class="offcanvas-lg offcanvas-start pe-lg-0 pe-xl-4" id="accountSidebar">

              <!-- Header -->
              <div class="offcanvas-header d-lg-block py-3 p-lg-0">
                <div class="d-flex align-items-center">
                  <div class="h5 d-flex justify-content-center align-items-center flex-shrink-0 text-primary bg-primary-subtle lh-1 rounded-circle mb-0" style="width: 3rem; height: 3rem">
                    <?php echo strtoupper(mb_substr($userData['first_name'], 0, 1) . mb_substr($userData['last_name'], 0, 1)); ?>
                  </div>
                  <div class="min-w-0 ps-3">
                    <h5 class="h6 mb-1"><?php echo htmlspecialchars($userData['first_name'] . ' ' . $userData['last_name']); ?></h5>
                    <div class="nav flex-nowrap text-nowrap min-w-0">
                      <a class="nav-link animate-underline text-body p-0" href="#bonusesModal" data-bs-toggle="modal">
                        <svg class="text-warning flex-shrink-0 me-2" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"><path d="M1.333 9.667H7.5V16h-5c-.64 0-1.167-.527-1.167-1.167V9.667zm13.334 0v5.167c0 .64-.527 1.167-1.167 1.167h-5V9.667h6.167zM0 5.833V7.5c0 .64.527 1.167 1.167 1.167h.167H7.5v-1-3H1.167C.527 4.667 0 5.193 0 5.833zm14.833-1.166H8.5v3 1h6.167.167C15.473 8.667 16 8.14 16 7.5V5.833c0-.64-.527-1.167-1.167-1.167z"/><path d="M8 5.363a.5.5 0 0 1-.495-.573C7.752 3.123 9.054-.03 12.219-.03c1.807.001 2.447.977 2.447 1.813 0 1.486-2.069 3.58-6.667 3.58zM12.219.971c-2.388 0-3.295 2.27-3.595 3.377 1.884-.088 3.072-.565 3.756-.971.949-.563 1.287-1.193 1.287-1.595 0-.599-.747-.811-1.447-.811z"/><path d="M8.001 5.363c-4.598 0-6.667-2.094-6.667-3.58 0-.836.641-1.812 2.448-1.812 3.165 0 4.467 3.153 4.713 4.819a.5.5 0 0 1-.495.573zM3.782.971c-.7 0-1.448.213-1.448.812 0 .851 1.489 2.403 5.042 2.566C7.076 3.241 6.169.971 3.782.971z"/></svg>
                        <span class="animate-target me-1"><?php echo $userData['loyalty_points'] ?? 0; ?> bonusuri</span>
                        <span class="text-body fw-normal text-truncate">disponibile</span>
                      </a>
                    </div>
                  </div>
                </div>
                <button type="button" class="btn-close d-lg-none" data-bs-dismiss="offcanvas" data-bs-target="#accountSidebar" aria-label="Close"></button>
              </div>

              <!-- Body (Navigation) -->
              <div class="offcanvas-body d-block pt-2 pt-lg-4 pb-lg-0">
                <nav class="list-group list-group-borderless">
                  <a class="list-group-item list-group-item-action d-flex align-items-center" href="/cont/comenzi">
                    <i class="ci-shopping-bag fs-base opacity-75 me-2"></i>
                    Comenzi
                  </a>
                  <a class="list-group-item list-group-item-action d-flex align-items-center pe-none active" href="/cont/wishlist">
                    <i class="ci-heart fs-base opacity-75 me-2"></i>
                    Lista de dorințe
                    <span class="badge bg-primary rounded-pill ms-auto"><?php echo count($wishlistItems); ?></span>
                  </a>
                  <a class="list-group-item list-group-item-action d-flex align-items-center" href="/cont/plata">
                    <i class="ci-credit-card fs-base opacity-75 me-2"></i>
                    Metode de plată
                  </a>
                  <a class="list-group-item list-group-item-action d-flex align-items-center" href="/cont/recenzii">
                    <i class="ci-star fs-base opacity-75 me-2"></i>
                    Recenziile mele
                  </a>
                </nav>
                <h6 class="pt-4 ps-2 ms-1">Gestionează contul</h6>
                <nav class="list-group list-group-borderless">
                  <a class="list-group-item list-group-item-action d-flex align-items-center" href="/cont/info">
                    <i class="ci-user fs-base opacity-75 me-2"></i>
                    Informații personale
                  </a>
                  <a class="list-group-item list-group-item-action d-flex align-items-center" href="/cont/adrese">
                    <i class="ci-map-pin fs-base opacity-75 me-2"></i>
                    Adrese
                  </a>
                  <a class="list-group-item list-group-item-action d-flex align-items-center" href="/cont/notificari">
                    <i class="ci-bell fs-base opacity-75 mt-1 me-2"></i>
                    Notificări
                  </a>
                </nav>
                <h6 class="pt-4 ps-2 ms-1">Servicii clienți</h6>
                <nav class="list-group list-group-borderless">
                  <a class="list-group-item list-group-item-action d-flex align-items-center" href="/contact">
                    <i class="ci-help-circle fs-base opacity-75 me-2"></i>
                    Centru de ajutor
                  </a>
                  <a class="list-group-item list-group-item-action d-flex align-items-center" href="/terms-and-conditions">
                    <i class="ci-info fs-base opacity-75 me-2"></i>
                    Termeni și condiții
                  </a>
                </nav>
                <nav class="list-group list-group-borderless pt-3">
                  <a class="list-group-item list-group-item-action d-flex align-items-center" href="/api/auth.php?action=logout">
                    <i class="ci-log-out fs-base opacity-75 me-2"></i>
                    Deconectare
                  </a>
                </nav>
              </div>
            </div>
          </aside>


          <!-- Wishlist content -->
          <div class="col-lg-9">
            <div class="ps-lg-3 ps-xl-0">

              <!-- Page title -->
              <h1 class="h2 mb-4">Lista de dorințe</h1>

              <?php if (empty($wishlistItems)): ?>
              <!-- Empty wishlist -->
              <div class="text-center py-5">
                <i class="ci-heart fs-1 text-body-secondary mb-3"></i>
                <h3 class="h5 mb-2">Lista ta de dorințe este goală</h3>
                <p class="text-body-secondary mb-4">Adaugă produse în lista de dorințe pentru a le salva pentru mai târziu.</p>
                <a class="btn btn-primary" href="/catalog">
                  Continuă cumpărăturile
                  <i class="ci-arrow-right fs-base ms-1 me-n1"></i>
                </a>
              </div>
              <?php else: ?>

              <!-- Sorting -->
              <div class="border-bottom pb-4 mb-4">
                <div class="row align-items-center justify-content-between">
                  <div class="col-sm-7 col-md-8 col-xxl-9 mb-3 mb-sm-0">
                    <h5 class="mb-0"><?php echo count($wishlistItems); ?> produse</h5>
                  </div>
                  <div class="col-sm-5 col-md-4 col-xxl-3">
                    <select class="form-select" id="sortWishlist" onchange="sortWishlist(this.value)">
                      <option value="date">După data adăugării</option>
                      <option value="price-asc">După preț crescător</option>
                      <option value="price-desc">După preț descrescător</option>
                      <option value="name">După nume</option>
                    </select>
                  </div>
                </div>
              </div>

              <!-- Wishlist items (Grid) -->
              <div class="row row-cols-2 row-cols-md-3 g-4" id="wishlistItems">
                <?php foreach ($wishlistItems as $item): ?>
                <?php
                $productData = $product->getProductById($item['product_id']);
                if (!$productData) continue;
                
                $displayPrice = $product->getProductPrice($productData, $b2bGroup);
                $originalPrice = $productData['sale_price'] ?? $productData['price'];
                $hasSale = !empty($productData['sale_price']) && $productData['sale_price'] < $productData['price'];
                $discountPercent = 0;
                if ($hasSale) {
                    $discountPercent = round((($productData['price'] - $productData['sale_price']) / $productData['price']) * 100);
                }
                
                $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;
                }
                
                $productUrl = '/produs/' . htmlspecialchars($productData['slug']);
                ?>
                <div class="col" data-product-id="<?php echo $item['product_id']; ?>" data-price="<?php echo $displayPrice; ?>" data-name="<?php echo htmlspecialchars($productData['name']); ?>">
                  <div class="product-card animate-underline hover-effect-opacity bg-body rounded">
                    <div class="position-relative">
                      <div class="position-absolute top-0 end-0 z-1 pt-1 pe-1 mt-2 me-2">
                        <form method="POST" class="d-inline" onsubmit="return confirm('Ești sigur că vrei să ștergi acest produs din lista de dorințe?');">
                          <input type="hidden" name="action" value="remove">
                          <input type="hidden" name="product_id" value="<?php echo $item['product_id']; ?>">
                          <button type="submit" class="btn btn-icon btn-ghost btn-danger border-0 p-0" aria-label="Șterge din lista de dorințe">
                            <i class="ci-trash fs-base"></i>
                          </button>
                        </form>
                      </div>
                      <a class="d-block rounded-top overflow-hidden p-3 p-sm-4" href="<?php echo $productUrl; ?>">
                        <?php if ($discountPercent > 0): ?>
                        <span class="badge bg-danger position-absolute top-0 start-0 mt-2 ms-2 mt-lg-3 ms-lg-3">-<?php echo $discountPercent; ?>%</span>
                        <?php endif; ?>
                        <div class="ratio" style="--cz-aspect-ratio: calc(240 / 258 * 100%)">
                          <img src="<?php echo htmlspecialchars($image); ?>" alt="<?php echo htmlspecialchars($productData['name']); ?>">
                        </div>
                      </a>
                    </div>
                    <div class="w-100 min-w-0 px-1 pb-2 px-sm-3 pb-sm-3">
                      <h3 class="pb-1 mb-2">
                        <a class="d-block fs-sm fw-medium text-truncate" href="<?php echo $productUrl; ?>">
                          <span class="animate-target"><?php echo htmlspecialchars($productData['name']); ?></span>
                        </a>
                      </h3>
                      <div class="d-flex align-items-center justify-content-between">
                        <div class="h5 lh-1 mb-0">
                          <?php echo number_format($displayPrice, 2); ?> RON
                          <?php if ($hasSale && $displayPrice == $productData['sale_price']): ?>
                          <del class="text-body-tertiary fs-sm fw-normal"><?php echo number_format($productData['price'], 2); ?> RON</del>
                          <?php endif; ?>
                        </div>
                        <form method="POST" class="d-inline">
                          <input type="hidden" name="action" value="add_to_cart">
                          <input type="hidden" name="product_id" value="<?php echo $item['product_id']; ?>">
                          <button type="submit" class="product-card-button btn btn-icon btn-secondary animate-slide-end ms-2" aria-label="Adaugă în coș" <?php echo ($productData['stock_quantity'] <= 0) ? 'disabled' : ''; ?>>
                            <i class="ci-shopping-cart fs-base animate-target"></i>
                          </button>
                        </form>
                      </div>
                      <?php if ($productData['stock_quantity'] <= 0): ?>
                      <div class="alert alert-warning mt-2 mb-0 py-1 px-2" role="alert">
                        <small>Stoc epuizat</small>
                      </div>
                      <?php elseif ($productData['stock_quantity'] < 10): ?>
                      <div class="alert alert-info mt-2 mb-0 py-1 px-2" role="alert">
                        <small>Doar <?php echo $productData['stock_quantity']; ?> rămase</small>
                      </div>
                      <?php endif; ?>
                    </div>
                  </div>
                </div>
                <?php endforeach; ?>
              </div>

              <!-- Add all to cart button -->
              <div class="text-center mt-4">
                <form method="POST" id="addAllToCartForm">
                  <input type="hidden" name="action" value="add_all_to_cart">
                  <button type="submit" class="btn btn-lg btn-primary">
                    <i class="ci-shopping-cart fs-base me-2"></i>
                    Adaugă toate în coș
                  </button>
                </form>
              </div>
              <?php endif; ?>
            </div>
          </div>
        </div>
      </div>
    </main>

<script>
function sortWishlist(sortBy) {
    const container = document.getElementById('wishlistItems');
    const items = Array.from(container.children);
    
    items.sort((a, b) => {
        switch(sortBy) {
            case 'price-asc':
                return parseFloat(a.dataset.price) - parseFloat(b.dataset.price);
            case 'price-desc':
                return parseFloat(b.dataset.price) - parseFloat(a.dataset.price);
            case 'name':
                return a.dataset.name.localeCompare(b.dataset.name);
            case 'date':
            default:
                return 0; // Already sorted by date from DB
        }
    });
    
    items.forEach(item => container.appendChild(item));
}

// Handle add all to cart
document.getElementById('addAllToCartForm')?.addEventListener('submit', function(e) {
    e.preventDefault();
    const items = document.querySelectorAll('#wishlistItems .col');
    let added = 0;
    
    items.forEach(item => {
        const form = item.querySelector('form[method="POST"]');
        if (form && form.querySelector('input[name="action"][value="add_to_cart"]')) {
            const formData = new FormData(form);
            fetch('/api/cart.php?action=add', {
                method: 'POST',
                body: formData
            }).then(() => {
                added++;
                if (added === items.length) {
                    window.location.href = '/cos';
                }
            });
        }
    });
    
    if (added === 0) {
        alert('Nu s-au putut adăuga produse în coș.');
    }
});
</script>

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

