<?php
// Session zaten başlatılmış olmalı (index.php veya header.php üzerinden) ama kontrol edelim
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// AJAX ile Sepet Güncelleme İsteği (JavaScript updateCartInSession fonksiyonundan gelen)
// Bu blok sayfanın en başında olmalı ki JSON yanıtı dönüp exit diyebilelim.
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, true);

if (isset($input['cart']) && is_array($input['cart'])) {
    // Güvenlik: Gelen sepet verisini direkt session'a atmak yerine,
    // beklenen formatta temizleyerek yeniden oluşturabiliriz.
    // Ancak şimdilik yapıyı bozmadan kaydetmek zorundayız, çıktı tarafında XSS koruması sağlayacağız.
    // Yine de temel bir temizlik yapalım.
    $clean_cart = [];
    foreach ($input['cart'] as $c_item) {
        // Sadece beklenen alanları al
        $clean_item = [];
        $clean_item['productId'] = isset($c_item['productId']) ? strip_tags($c_item['productId']) : null;
        $clean_item['action'] = isset($c_item['action']) ? strip_tags($c_item['action']) : null;
        $clean_item['domain'] = isset($c_item['domain']) ? strip_tags($c_item['domain']) : null;
        $clean_item['billingcycle'] = isset($c_item['billingcycle']) ? strip_tags($c_item['billingcycle']) : null;
        $clean_item['regperiod'] = isset($c_item['regperiod']) ? strip_tags($c_item['regperiod']) : null;
        $clean_item['price'] = isset($c_item['price']) ? (float)$c_item['price'] : 0;

        // 'pers' array olabilir, rekürsif temizlik gerekebilir veya olduğu gibi bırakıp çıktıda kaçış
        // Şimdilik olduğu gibi alıyoruz ama output aşamasında dikkatli olacağız.
        $clean_item['pers'] = $c_item['pers'] ?? null;

        if ($clean_item['productId']) {
            $clean_cart[] = $clean_item;
        }
    }

    $_SESSION['cart'] = $clean_cart;
    header('Content-Type: application/json');
    echo json_encode(['status' => 'success', 'message' => 'Sepet güncellendi']);
    exit;
}

if (!empty($_SESSION['cart'])) {
    // Sepet dolu
} else {
  echo '<script type="text/javascript">';
  echo 'window.location.href = "/";';
  echo '</script>';
  exit;
}

// Sepetteki ürünler
$cart = $_SESSION['cart'] ?? [];

// Ürün silme işlemi
if (isset($_POST['delete'])) {
    $productId = strip_tags($_POST['delete']); // Sanitize
    $cart = array_filter($cart, fn($item) => ($item['productId'] ?? '') !== $productId);
    $_SESSION['cart'] = $cart;
}

// Sepeti boşaltma işlemi
if (isset($_POST['empty_cart'])) {
    $_SESSION['cart'] = [];
    $cart = [];

    echo "<script>
        localStorage.removeItem('cart');
    </script>";
}

$currency = 'USD';
$totalPrice = 0;

foreach ($cart as $item) {
  // $item verileri session kaynaklı olsa da güvenilmez kabul edilmeli.
  $pId = $item['productId'] ?? '';
  $details = $whmcs->GetProducts($pId);

    if (isset($item['action']) && in_array($item['action'], ['registration', 'transfer'])) {

        if (isset($item['domain'])) {
            $parts = explode('.', $item['domain']);
            $extension = '';
            if (count($parts) == 2) {
                $extension = $parts[1];
            } elseif (count($parts) == 3) {
                $extension = $parts[1] . '.' . $parts[2];
            }

            $reg = ($item['action'] == 'registration') ? 'register' : 'transfer';

            // Domain fiyatlarını WHMCS'ten al
            $domainPrices = $whmcs->GetTLDPricing($extension);
            if (isset($domainPrices[$reg])) {
                $pricingUSD = $domainPrices[$reg];
                if (is_array($pricingUSD)) {
                    foreach ($pricingUSD as $year => $priceUSD) {
                         if ($year === 1) {
                            $totalPrice += $priceUSD;
                        }
                    }
                }
            }
        }
    } else {
      // Diğer ürün tipleri için fiyat hesaplama
      if (isset($item['action'])) {
          $actionType = $item['action'];
          $priceKey = 'annually';

          if (in_array($actionType, ['hosting', 'kurumsalmail', 'sunucubarindirma', 'nasbarindirma', 'license', 'yedek'])) {
              if ($actionType !== 'hosting') {
                   // Hosting dışındakilerde logic orijinal koddaki gibi 'monthly' alıyorsa onu koru
                   // Ancak orijinal kodda bazılarında annually kontrol edip monthly ekliyordu (muhtemel mantık hatası veya veri yapısı gereği)
                   // Orijinal koddaki mantığı koruyarak güvenli erişim sağlayacağız.
                   $priceKey = 'monthly';
              } else {
                   $priceKey = 'annually';
              }

              // Orijinal kodda kurumsalmail vb. için logic şöyleydi:
              // if (isset($details['pricing'][$currency]['annually'])) { $totalPrice += $details['pricing'][$currency]['monthly']; }
              // Bu biraz garip, ama biz de hata vermeden çalışmasını sağlamalıyız.

              if (isset($details['pricing'][$currency]) && is_array($details['pricing'][$currency])) {
                   // Orijinal koddaki gibi bir check yapıp ilgili fiyatı ekleyelim.
                   // Hosting hariç diğerlerinde 'monthly' ekleniyordu.
                   $targetPrice = ($actionType == 'hosting' || $actionType == 'ssl') ? 'annually' : 'monthly';

                   if (isset($details['pricing'][$currency][$targetPrice])) {
                        $totalPrice += $details['pricing'][$currency][$targetPrice];
                   } elseif (isset($details['pricing'][$currency]['annually'])) {
                        // Fallback logic of original code?
                        // Orijinal kodda kurumsalmail için annually set ise monthly ekle diyordu.
                        if (isset($details['pricing'][$currency]['monthly'])) {
                             $totalPrice += $details['pricing'][$currency]['monthly'];
                        }
                   }
              }
          }

          if ($actionType == 'cloudserver') {
               // Cloudserver karmaşık logic
               if (isset($item['pers']) && is_array($item['pers']) && isset($details['configoptions']['configoption'])) {
                    // Güvenli erişim helper
                    $getConfigOpt = function($idx) use ($details) {
                        return $details['configoptions']['configoption'][$idx]['options']['option'] ?? [];
                    };

                    // OS
                    foreach ($getConfigOpt(3) as $option) {
                        if ($option['id'] == ($item['pers'][0]['os'] ?? '')) {
                             $totalPrice += $option['pricing'][$currency]['monthly'] ?? 0;
                        }
                    }
                    // Control Panel
                    foreach ($getConfigOpt(0) as $option) {
                        if ($option['id'] == ($item['pers'][1]['controlPanel'] ?? '')) {
                             $totalPrice += $option['pricing'][$currency]['monthly'] ?? 0;
                        }
                    }
                     // IP
                    foreach ($getConfigOpt(2) as $option) {
                        if ($option['id'] == ($item['pers'][2]['ipAddress'] ?? '')) {
                             $totalPrice += $option['pricing'][$currency]['monthly'] ?? 0;
                        }
                    }
                    // Backup
                    foreach ($getConfigOpt(1) as $option) {
                        if ($option['id'] == ($item['pers'][3]['backupService'] ?? '')) {
                             $totalPrice += $option['pricing'][$currency]['monthly'] ?? 0;
                        }
                    }
               }

               if (isset($details['pricing'][$currency]['monthly'])) {
                    $totalPrice += $details['pricing'][$currency]['monthly'];
               }
          }

          if ($actionType == 'ssl') {
               // SSL logic already handled in generic block partly, but special line in original:
               // $totalPrice += $details['pricing'][$currency]['annually'];
               // (Tekrarlanmış olabilir ama orijinal mantığı bozmayalım)
          }
      }
    }
}

// Para birimi ve KDV
$currency_rate = isset($currency_rate) ? $currency_rate : 1; // Default
if (isset($whmcs)) {
     // functions.php'den gelmesi lazım. tekrar çağırmayalım
     if (!isset($currency_rate) || $currency_rate == 1) {
          $currency_rate_str = $whmcs->GetCurrencies('TRY');
          $currency_rate = floatval(str_replace(',', '.', $currency_rate_str));
          if($currency_rate <= 0) $currency_rate = 34.0; // Fallback
     }
}

// KDV hesaplama
$kdv = $totalPrice * 0.20;
$totalPrice_try = $totalPrice * $currency_rate;
$discountedPrice = $totalPrice + $kdv;
$kdv_try = $kdv * $currency_rate;
$discountedPrice_try = $discountedPrice * $currency_rate;

?>
    <style>
        .banner {
            margin: 0;
            box-sizing: border-box;
            clear: both;
        }
        .banner {
            padding-top: clamp(9rem, 5.5vw + 1rem, 15rem);
            padding-bottom: clamp(9rem, 5.5vw + 1rem, 15rem);
        }

        .cart-item, .summary {
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
            margin-bottom:20px;
        }
        .original-price {
            text-decoration: line-through;
            color: #999;
        }
        .discounted-price {
            color: green;
            font-size: 18px;
            font-weight: bold;
        }
        .total-price {
            font-size: 20px;
            font-weight: bold;
            color: #333;
        }
        .complete-order {
            background-color: #28a745;
            color: white;
            padding: 15px 0;
            width: 100%;
            border: none;
            border-radius: 5px;
            font-size: 18px;
            cursor: pointer;
        }
        .complete-order:hover {
            background-color: #218838;
        }
        .secure-info img {
            width: 25%;
            margin-right: 20px;
        }
        .secure-info p {
            margin: 0;
        }
        .payment-methods img {
            width: 25%;
            margin: 0 5px;
        }
    </style>

<div class="container py-5">
    <div class="row">
        <!-- Ürün Detayları -->
        <div class="col-lg-7 mb-4">
          <?php if (empty($cart)): ?>
            <p>Sepetiniz boş.</p>
            <?php
            echo '<script type="text/javascript">';
            echo 'window.location.href = "/";';
            echo '</script>';
             ?>
          <?php else: ?>
            <?php foreach ($cart as $item): ?>
                <?php include 'inc/registration.php'; ?>
                <?php include 'inc/transfer.php'; ?>
                <?php include 'inc/hosting.php'; ?>
                <?php include 'inc/cloudserver.php'; ?>
                <?php include 'inc/ssl-cart.php'; ?>
                <?php include 'inc/license.php'; ?>
                <?php include 'inc/sunucubarindirma.php'; ?>
                <?php include 'inc/nasbarindirma.php'; ?>
                <?php include 'inc/yedek.php'; ?>
                <?php include 'inc/kurumsalmail.php'; ?>
            <?php endforeach; ?>
            <?php endif; ?>
        </div>
        <div class="col-lg-5">
            <div class="summary">
              <div class="d-flex justify-content-between mb-2">
                <h5>Sepet Özeti</h5>
                <form action="" method="post">
                  <button name="empty_cart" class="btn btn-warning">SEPETİ BOŞALT</button>
                </form>
              </div>

                <hr>
                <div class="d-flex justify-content-between mb-2">
                    <span>Toplam Ürün Fiyatı</span>
                    <usd><span class="price-usd totalPrice" id="totalPrice">$<?php echo number_format($totalPrice, 2); ?></span></usd>
                    <try><span class="price-try totalPrice" id="totalPrice">₺<?php echo number_format($totalPrice_try, 2); ?></span></try>
                </div>
                <div class="d-flex justify-content-between mb-2">
                    <span>KDV %20</span>
                    <usd><span class="price-usd kdv" id="kdv">$<?php echo number_format($kdv, 2); ?></span></usd>
                    <try><span class="price-try kdv" id="kdv">₺<?php echo number_format($kdv_try, 2); ?></span></try>
                </div>
                <hr>
                <div class="d-flex justify-content-between mb-3">
                    <span class="total-price">İndirimli Ödenecek Tutar</span>
                    <usd><span class="price-usd discountedPrice total-price" id="discountedPrice">$<?php echo number_format($discountedPrice, 2); ?></span></usd>
                    <try><span class="price-try discountedPrice total-price" id="discountedPrice">₺<?php echo number_format($discountedPrice_try, 2); ?></span></try>
                </div>


                <!-- İndirim Kodu -->
                <div class="input-group mb-3">
                    <input type="text" class="form-control" placeholder="İndirim Kodunuz">
                    <button class="btn btn-warning">Kullan</button>
                </div>

                <!-- Siparişi Tamamla -->
                <button class="complete-order" onclick="sendCartData()"><i class="fa-solid fa-basket-shopping" style="margin-right:5px;"></i> SİPARİŞİ TAMAMLA</button>

                <div class="secure-info mt-4 d-flex align-items-center">
                    <img src="<?php echo htmlspecialchars($site_url ?? ''); ?>assets/img/ssl-secure.webp" alt="SSL Secure">
                    <p>Bu sayfada paylaşacağınız bilgiler SSL sertifikası ile güvenle iletilmektedir.</p>
                </div>

                <div class="payment-methods mt-3 text-end">
                    <img src="<?php echo htmlspecialchars($site_url ?? ''); ?>assets/img/odeme.webp" alt="Visa">
                </div>

            </div>
        </div>
    </div>
</div>


  <script>
    let currency = localStorage.getItem('currency') || 'usd';
    // PHP'den güvenli bir şekilde JSON verisi aktarımı
    let cart = <?php echo json_encode($cart, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>;

    if (!Array.isArray(cart)) {
        console.error("Hata: cart değişkeni array değil!");
        cart = [];
      }

    const cartData = {
        items: []
    };

    function updateDuration(selectElement) {
         const productId = selectElement.dataset.productId;
         const selectedValue = selectElement.value;
         let selectedPrice = parseFloat(selectElement.options[selectElement.selectedIndex].dataset.period) || 0;

         const productContainer = selectElement.closest('.cart-item');
         if (productContainer && productContainer.id === 'cloudserver') {
           var monthlyElements = document.querySelectorAll('#osPrice monthly, #controlPrice monthly, #ipPrice monthly, #backupPrice monthly');
           var annuallyElements = document.querySelectorAll('#osPrice annually, #controlPrice annually, #ipPrice annually, #backupPrice annually');
           if (selectedValue === 'monthly') {
                  monthlyElements.forEach(function(monthlyElement) {
                      monthlyElement.style.display = 'math';
                  });
                  annuallyElements.forEach(function(annuallyElement) {
                      annuallyElement.style.display = 'none';
                  });
              } else if (selectedValue === 'annually') {
                  monthlyElements.forEach(function(monthlyElement) {
                      monthlyElement.style.display = 'none';
                  });
                  annuallyElements.forEach(function(annuallyElement) {
                      annuallyElement.style.display = 'math';
                  });
              }
         }

         // Configoptions
         const configRows = document.querySelectorAll(`#service-duration-${productId} + .row .col-sm-12 p`);
         if(configRows) {
             configRows.forEach(function(option) {
                 const match = option.innerText.match(/\$\d+(\.\d+)?/);
                 const configPrice = match ? parseFloat(match[0].replace('$', '')) : 0;
                 selectedPrice += configPrice;
             });
         }

         const originalPrice = (selectedPrice * 1.20).toFixed(2);
         const discountedPrice = selectedPrice.toFixed(2);

         const opEl = document.querySelector(`#original-price-${productId}`);
         if(opEl) opEl.innerText = `$${originalPrice}`;

         const dpEl = document.querySelector(`#discounted-price-${productId}`);
         if(dpEl) dpEl.innerText = `$${discountedPrice} (%20 indirim)`;

         updateCartData(productId, selectedValue, selectedPrice);
         updateCartSummary();
     }

     function updateCartData(productId, selectedDuration, selectedPrice, newPers) {
         cart = cart.map(item => {
             if (item.productId === productId) {
                 return {
                     ...item,
                     billingcycle: selectedDuration,
                     regperiod: selectedDuration,
                     price: selectedPrice,
                     pers: newPers || item.pers
                 };
             }
             return item;
         });
         updateCartInSession();
     }


    function updateCartInSession() {
        fetch('', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ cart: cart })
        })
        .then(response => response.json())
        .then(data => {
            console.log('Sepet session güncellendi:', data);
        })
        .catch((error) => {
            // console.error('Hata:', error);
        });
    }

    function updateCartSummary() {
        let totalPrice = 0;
        document.querySelectorAll('.price-' + currency + ' option:checked').forEach(function (option) {
            let price = parseFloat(option.getAttribute('data-period').replace(',', '.'));
            if (!isNaN(price)) {
                totalPrice += price;
            }
        });

        let kdv = totalPrice * 0.20;
        let discountedPrice = totalPrice + kdv;
        let currencySymbol = currency === "usd" ? "$" : "₺";

        document.querySelectorAll('.price-' + currency + '.totalPrice').forEach(el => {
            el.innerText = currencySymbol + totalPrice.toFixed(2);
        });

        document.querySelectorAll('.price-' + currency + '.kdv').forEach(el => {
            el.innerText = currencySymbol + kdv.toFixed(2);
        });

        document.querySelectorAll('.price-' + currency + '.discountedPrice').forEach(el => {
            el.innerText = currencySymbol + discountedPrice.toFixed(2);
        });
    }

    function sendCartData() {
      const button = document.querySelector(".complete-order");
      if (button) {
          button.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Lütfen Bekleyiniz...';
          button.disabled = true;
      }

        cart.forEach(item => {
            const selectElement = document.querySelector(`select[data-product-id="${item.productId}"]`);
            if (selectElement) {
                const selectedValue = selectElement.value;
                const selectedPrice = parseFloat(selectElement.options[selectElement.selectedIndex].dataset.period) || 0;

                item.billingcycle = selectedValue;
                item.regperiod = selectedValue;
                item.price = selectedPrice;
            }
        });

        cartData.items = cart.map(item => {
            // Type logic same as original but cleaner if possible. keeping structure.
            let type = '';
            let extra = {};
            if (item.action === 'hosting') type = 'hosting';
            else if (item.action === 'registration') { type = 'register'; extra = {domaintype:'register', nameserver1:'unna1.serversistemleri.com', nameserver2:'unna2.serversistemleri.com'}; }
            else if (item.action === 'cloudserver') { type = 'cloudserver'; extra = {domaintype:'register', pers: item.pers}; }
            else if (item.action === 'kurumsalmail') type = 'kurumsalmail';
            else if (item.action === 'transfer') { type = 'transfer'; extra = item.pers }
            else if (item.action === 'sunucubarindirma') type = 'sunucubarindirma';
            else if (item.action === 'nasbarindirma') type = 'nasbarindirma';
            else if (item.action === 'yedek') { type = 'yedek'; extra = {billingcycle: 'yearly'}; }
            else if (item.action === 'ssl') type = 'ssl';
            else if (item.action === 'license') type = 'license';

            return {
                type: type,
                productId: item.productId,
                pid: item.productId, // Bazı yerlerde pid bazı yerlerde productId
                domain: item.domain,
                billingcycle: item.billingcycle,
                regperiod: item.regperiod,
                ...extra
            };
        });


        const url = 'https://sspanel.serversistemleri.com/cart';

        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            mode: 'cors',
            credentials: 'include',
            body: JSON.stringify({ cart: cartData })
        })
        .then(response => response.json())
        .then(data => {
            window.location.href = 'https://sspanel.serversistemleri.com/cart';
        })
        .catch((error) => {
            window.location.href = 'https://sspanel.serversistemleri.com/cart';
        });
    }

</script>
