<?php
/**
 * Checkout Shipping Address Step 2
 * Converted from checkout-v1-shipping.html
 * Second step of checkout - shipping address
 */

$pageTitle = 'Cartzilla | Finalizare Comandă - Adresă 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;
}

// Check if postcode is set (from step 1)
$postcode = $_SESSION['checkout_postcode'] ?? '';
if (empty($postcode)) {
    header('Location: /checkout/livrare');
    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
$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'];
    }
}

// Calculate shipping cost (example: 25 RON standard, free over 500 RON)
$freeShippingThreshold = 500;
$shippingCost = $subtotal >= $freeShippingThreshold ? 0 : 25;

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

// Get saved addresses for user
// Get saved addresses for user (filter shipping addresses if needed)
$allAddresses = $userId ? $userObj->getUserAddresses($userId) : [];
$savedAddresses = $allAddresses; // All addresses can be used for shipping
$userData = $userId ? $userObj->getUserById($userId) : null;

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $addressData = [
        'first_name' => $_POST['first_name'] ?? '',
        'last_name' => $_POST['last_name'] ?? '',
        'email' => $_POST['email'] ?? '',
        'phone' => $_POST['phone'] ?? '',
        'city' => $_POST['city'] ?? '',
        'county' => $_POST['county'] ?? '',
        'postal_code' => $_POST['postal_code'] ?? $postcode,
        'address_line1' => $_POST['address_line1'] ?? '',
        'address_line2' => $_POST['address_line2'] ?? '',
        'country' => $_POST['country'] ?? 'Romania',
        'type' => 'shipping',
        'order_type' => 'physical',
        'is_default' => isset($_POST['save_address']) ? 1 : 0
    ];
    
    // Save address to session
    $_SESSION['checkout_shipping_address'] = $addressData;
    
    // If user is logged in and wants to save address
    if ($userId && isset($_POST['save_address'])) {
        $userObj->addAddress($userId, $addressData);
    }
    
    // Redirect to payment step
    header('Location: /checkout/plata');
    exit;
}

// Pre-fill form with saved data or user data
$formData = $_SESSION['checkout_shipping_address'] ?? [];
if (empty($formData) && $userData) {
    $formData = [
        'first_name' => $userData['first_name'] ?? '',
        'last_name' => $userData['last_name'] ?? '',
        'email' => $userData['email'] ?? '',
        'phone' => $userData['phone'] ?? ''
    ];
}

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

// Romanian counties list
$counties = [
    'Alba', 'Arad', 'Argeș', 'Bacău', 'Bihor', 'Bistrița-Năsăud', 'Botoșani', 'Brașov', 'Brăila',
    'București', 'Buzău', 'Caraș-Severin', 'Călărași', 'Cluj', 'Constanța', 'Covasna', 'Dâmbovița',
    'Dolj', 'Galați', 'Giurgiu', 'Gorj', 'Harghita', 'Hunedoara', 'Ialomița', 'Iași', 'Ilfov',
    'Maramureș', 'Mehedinți', 'Mureș', 'Neamț', 'Olt', 'Prahova', 'Sălaj', 'Satu Mare', 'Sibiu',
    'Suceava', 'Teleorman', 'Timiș', 'Tulcea', 'Vâlcea', 'Vaslui', 'Vrancea'
];

// Romanian cities list (major cities)
$cities = [
    'București', 'Cluj-Napoca', 'Timișoara', 'Iași', 'Constanța', 'Craiova', 'Brașov', 'Galați',
    'Ploiești', 'Oradea', 'Brăila', 'Arad', 'Pitești', 'Sibiu', 'Bacău', 'Târgu Mureș',
    'Baia Mare', 'Buzău', 'Satu Mare', 'Botoșani', 'Râmnicu Vâlcea', 'Suceava', 'Piatra Neamț',
    'Drobeta-Turnu Severin', 'Focșani', 'Târgu Jiu', 'Tulcea', 'Târgoviște', 'Reșița', 'Bistrița',
    'Slatina', 'Hunedoara', 'Vaslui', 'Giurgiu', 'Turda', 'Mediaș', 'Slobozia', 'Alexandria'
];
?>

    <!-- 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">
          <div class="col-lg-8 col-xl-7 mb-5 mb-lg-0">
            <div class="accordion d-flex flex-column gap-5 pe-lg-4 pe-xl-0" id="checkout">

              <!-- Delivery info overview + Edit button -->
              <div class="accordion-item d-flex align-items-start border-0">
                <div class="d-flex align-items-center justify-content-center bg-body-secondary text-dark-emphasis rounded-circle flex-shrink-0" style="width: 2rem; height: 2rem; margin-top: -.125rem">
                  <i class="ci-check fs-base"></i>
                </div>
                <div class="w-100 ps-3 ps-md-4">
                  <div class="d-flex align-items-center">
                    <h2 class="accordion-header h5 mb-0 me-3" id="deliveryInfoHeading">
                      <span class="d-none d-lg-inline">Informații livrare</span>
                      <button type="button" class="accordion-button collapsed fs-5 d-lg-none py-1" data-bs-toggle="collapse" data-bs-target="#deliveryInfo" aria-expanded="false" aria-controls="deliveryInfo">
                        <span class="me-2">Informații livrare</span>
                      </button>
                    </h2>
                    <div class="nav ms-auto">
                      <a class="nav-link text-decoration-underline p-0" href="/checkout/livrare">Editează</a>
                    </div>
                  </div>
                  <div class="accordion-collapse collapse d-lg-block" id="deliveryInfo" aria-labelledby="deliveryInfoHeading" data-bs-parent="#checkout">
                    <div class="accordion-body p-0 pt-3 pt-md-4">
                      <h3 class="fs-sm mb-2">Cod poștal</h3>
                      <p class="fs-sm"><?php echo htmlspecialchars($postcode); ?></p>
                      <h3 class="fs-sm mb-2">Data estimată de livrare</h3>
                      <div class="d-flex align-items-center fs-sm">
                        <?php
                        $deliveryDate = date('l, j', strtotime('+3 days'));
                        $days = ['Monday' => 'Luni', 'Tuesday' => 'Marți', 'Wednesday' => 'Miercuri', 'Thursday' => 'Joi', 'Friday' => 'Vineri', 'Saturday' => 'Sâmbătă', 'Sunday' => 'Duminică'];
                        $dayName = $days[date('l', strtotime('+3 days'))] ?? date('l', strtotime('+3 days'));
                        echo $dayName . ', ' . date('j', strtotime('+3 days'));
                        ?>
                        <span class="opacity-40 mx-2">|</span>
                        09:00 - 17:00
                      </div>
                    </div>
                  </div>
                </div>
              </div>


              <!-- Shipping address form -->
              <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">2</div>
                <div class="w-100 ps-3 ps-md-4">
                  <h1 class="h5 mb-md-4">Adresă livrare</h1>
                  
                  <?php if (!empty($savedAddresses)): ?>
                  <!-- Saved addresses -->
                  <div class="mb-4">
                    <label class="form-label mb-2">Selectează adresă salvată</label>
                    <div class="row g-2">
                      <?php foreach ($savedAddresses as $savedAddr): ?>
                      <div class="col-12">
                        <div class="card">
                          <div class="card-body">
                            <div class="form-check">
                              <input class="form-check-input" type="radio" name="saved_address" id="address_<?php echo $savedAddr['id']; ?>" value="<?php echo $savedAddr['id']; ?>" onchange="fillSavedAddress(<?php echo htmlspecialchars(json_encode($savedAddr)); ?>)">
                              <label class="form-check-label w-100" for="address_<?php echo $savedAddr['id']; ?>">
                                <strong><?php echo htmlspecialchars($savedAddr['first_name'] . ' ' . $savedAddr['last_name']); ?></strong><br>
                                <?php echo htmlspecialchars($savedAddr['address_line1']); ?><br>
                                <?php if ($savedAddr['address_line2']): ?>
                                <?php echo htmlspecialchars($savedAddr['address_line2']); ?><br>
                                <?php endif; ?>
                                <?php echo htmlspecialchars($savedAddr['city'] . ', ' . $savedAddr['county'] . ' ' . $savedAddr['postal_code']); ?>
                              </label>
                            </div>
                          </div>
                        </div>
                      </div>
                      <?php endforeach; ?>
                    </div>
                    <div class="text-center mt-3">
                      <button type="button" class="btn btn-sm btn-outline-secondary" onclick="document.getElementById('newAddressForm').style.display = 'block'; this.style.display = 'none';">
                        Folosește adresă nouă
                      </button>
                    </div>
                  </div>
                  <?php endif; ?>
                  
                  <form method="POST" class="needs-validation" id="newAddressForm" novalidate <?php echo !empty($savedAddresses) ? 'style="display: none;"' : ''; ?>>
                    <div class="row row-cols-1 row-cols-sm-2 g-3 g-sm-4 mb-4">
                      <div class="col">
                        <label for="shipping-fn" class="form-label">Prenume <span class="text-danger">*</span></label>
                        <input type="text" class="form-control form-control-lg" id="shipping-fn" name="first_name" value="<?php echo htmlspecialchars($formData['first_name'] ?? ''); ?>" required>
                      </div>
                      <div class="col">
                        <label for="shipping-ln" class="form-label">Nume <span class="text-danger">*</span></label>
                        <input type="text" class="form-control form-control-lg" id="shipping-ln" name="last_name" value="<?php echo htmlspecialchars($formData['last_name'] ?? ''); ?>" required>
                      </div>
                      <div class="col">
                        <label for="shipping-email" class="form-label">Adresă email <span class="text-danger">*</span></label>
                        <input type="email" class="form-control form-control-lg" id="shipping-email" name="email" value="<?php echo htmlspecialchars($formData['email'] ?? ''); ?>" required>
                      </div>
                      <div class="col">
                        <label for="shipping-mobile" class="form-label">Număr telefon</label>
                        <input type="text" class="form-control form-control-lg" id="shipping-mobile" name="phone" value="<?php echo htmlspecialchars($formData['phone'] ?? ''); ?>">
                      </div>
                      <div class="col">
                        <label for="shipping-city" class="form-label">Oraș <span class="text-danger">*</span></label>
                        <select class="form-select form-select-lg" id="shipping-city" name="city" required>
                          <option value="">Selectează orașul</option>
                          <?php foreach ($cities as $city): ?>
                          <option value="<?php echo htmlspecialchars($city); ?>" <?php echo (($formData['city'] ?? '') === $city) ? 'selected' : ''; ?>><?php echo htmlspecialchars($city); ?></option>
                          <?php endforeach; ?>
                        </select>
                      </div>
                      <div class="col">
                        <label for="shipping-county" class="form-label">Județ <span class="text-danger">*</span></label>
                        <select class="form-select form-select-lg" id="shipping-county" name="county" required>
                          <option value="">Selectează județul</option>
                          <?php foreach ($counties as $county): ?>
                          <option value="<?php echo htmlspecialchars($county); ?>" <?php echo (($formData['county'] ?? '') === $county) ? 'selected' : ''; ?>><?php echo htmlspecialchars($county); ?></option>
                          <?php endforeach; ?>
                        </select>
                      </div>
                      <div class="col">
                        <label for="shipping-postcode" class="form-label">Cod poștal <span class="text-danger">*</span></label>
                        <input type="text" class="form-control form-control-lg" id="shipping-postcode" name="postal_code" value="<?php echo htmlspecialchars($postcode); ?>" required>
                      </div>
                    </div>
                    <div class="mb-3">
                      <label for="shipping-address" class="form-label">Stradă și număr <span class="text-danger">*</span></label>
                      <input type="text" class="form-control form-control-lg" id="shipping-address" name="address_line1" value="<?php echo htmlspecialchars($formData['address_line1'] ?? ''); ?>" required>
                    </div>
                    <div class="mb-3" id="addressLine2Container" style="display: none;">
                      <label for="shipping-address2" class="form-label">Adresă linia 2</label>
                      <input type="text" class="form-control form-control-lg" id="shipping-address2" name="address_line2" value="<?php echo htmlspecialchars($formData['address_line2'] ?? ''); ?>">
                    </div>
                    <div class="nav mb-4">
                      <a class="nav-link px-0" href="#!" onclick="document.getElementById('addressLine2Container').style.display = 'block'; this.style.display = 'none'; return false;">
                        Adaugă linie adresă
                        <i class="ci-plus fs-base ms-1"></i>
                      </a>
                    </div>
                    <?php if ($userId): ?>
                    <div class="form-check mb-lg-4">
                      <input type="checkbox" class="form-check-input" id="save_address" name="save_address" value="1">
                      <label for="save_address" class="form-check-label">Salvează această adresă pentru comenzile viitoare</label>
                    </div>
                    <?php endif; ?>
                    <h3 class="h6">
                      Adresă facturare
                      <i class="ci-info text-body-secondary align-middle ms-2" data-bs-toggle="popover" data-bs-trigger="hover" data-bs-custom-class="popover-sm" data-bs-content="Debifează caseta de mai jos dacă adresa de facturare ar trebui să fie diferită de adresa de livrare."></i>
                    </h3>
                    <div class="form-check mb-lg-4">
                      <input type="checkbox" class="form-check-input" id="same-address" checked>
                      <label for="same-address" class="form-check-label">La fel ca adresa de livrare</label>
                    </div>
                    <button type="submit" class="btn btn-lg btn-primary w-100 d-none d-lg-flex">
                      Continuă
                      <i class="ci-chevron-right fs-lg ms-1 me-n1"></i>
                    </button>
                    <button type="submit" class="btn btn-lg btn-primary w-100 d-lg-none">
                      Continuă
                      <i class="ci-chevron-right fs-lg ms-1 me-n1"></i>
                    </button>
                  </form>
                </div>
              </div>

              <!-- Payment -->
              <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">
                        <?php if ($shippingCost == 0): ?>
                        <span class="text-success">Gratuit</span>
                        <?php else: ?>
                        <?php echo number_format($shippingCost, 2); ?> RON
                        <?php endif; ?>
                      </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
              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>

<script>
function fillSavedAddress(address) {
    document.getElementById('shipping-fn').value = address.first_name || '';
    document.getElementById('shipping-ln').value = address.last_name || '';
    document.getElementById('shipping-email').value = address.email || '';
    document.getElementById('shipping-mobile').value = address.phone || '';
    document.getElementById('shipping-city').value = address.city || '';
    document.getElementById('shipping-county').value = address.county || '';
    document.getElementById('shipping-postcode').value = address.postal_code || '';
    document.getElementById('shipping-address').value = address.address_line1 || '';
    if (address.address_line2) {
        document.getElementById('shipping-address2').value = address.address_line2 || '';
        document.getElementById('addressLine2Container').style.display = 'block';
    }
    document.getElementById('newAddressForm').style.display = 'block';
}
</script>

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

