<?php
/**
 * Checkout Delivery Info Step 1
 * Converted from checkout-v1-delivery-1.html
 * First step of checkout - delivery information
 */

$pageTitle = 'Cartzilla | Finalizare Comandă - Informații Livrare';
$pageDescription = 'Cartzilla - Magazin Online E-Commerce';

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

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

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

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

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

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

// Calculate totals (same as cart page)
$subtotal = 0;
$savings = 0;
$itemCount = 0;

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

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

// Handle form submission
$postcode = $_POST['postcode'] ?? $_SESSION['checkout_postcode'] ?? '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['postcode'])) {
    $_SESSION['checkout_postcode'] = $_POST['postcode'];
    // Redirect to next step
    header('Location: /checkout/livrare');
    exit;
}

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

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

          <!-- Delivery info (Step 1) -->
          <div class="col-lg-8 col-xl-7 mb-5 mb-lg-0">
            <div class="d-flex flex-column gap-5 pe-lg-4 pe-xl-0">
              <div class="d-flex align-items-start">
                <div class="d-flex align-items-center justify-content-center bg-primary text-white rounded-circle fs-sm fw-semibold lh-1 flex-shrink-0" style="width: 2rem; height: 2rem; margin-top: -.125rem">1</div>
                <div class="w-100 ps-3 ps-md-4">
                  <h1 class="h5 mb-md-4">Informații livrare</h1>
                  <div class="ms-n5 ms-sm-0">
                    <p class="fs-sm mb-md-4">Introdu codul poștal pentru a vedea opțiunile de livrare disponibile în zona ta.</p>
                    <form method="POST" class="d-flex flex-column flex-md-row align-items-md-end gap-3 gap-xl-4">
                      <div class="w-100">
                        <label for="postcode" class="form-label">Cod poștal</label>
                        <input type="text" class="form-control form-control-lg" id="postcode" name="postcode" placeholder="ex. 010001" value="<?php echo htmlspecialchars($postcode); ?>" required>
                      </div>
                      <button type="submit" class="btn btn-lg btn-primary">
                        Calculează cost și disponibilitate
                        <i class="ci-chevron-right fs-lg ms-1 me-n1"></i>
                      </button>
                    </form>
                  </div>
                </div>
              </div>
              <div class="d-flex align-items-start">
                <div class="d-flex align-items-center justify-content-center bg-body-secondary text-body-secondary rounded-circle fs-sm fw-semibold lh-1 flex-shrink-0" style="width: 2rem; height: 2rem; margin-top: -.125rem">2</div>
                <h2 class="h5 text-body-secondary ps-3 ps-md-4 mb-0">Adresă livrare</h2>
              </div>
              <div class="d-flex align-items-start">
                <div class="d-flex align-items-center justify-content-center bg-body-secondary text-body-secondary rounded-circle fs-sm fw-semibold lh-1 flex-shrink-0" style="width: 2rem; height: 2rem; margin-top: -.125rem">3</div>
                <h2 class="h5 text-body-secondary ps-3 ps-md-4 mb-0">Plată</h2>
              </div>
            </div>
          </div>


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

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

