<?php
session_start();
ob_start();
error_reporting(0);
$basket = $_SESSION['basket'] ?? [];
include_once('../inc/helper.php');

$basket_json = json_encode($basket);

// Check your $db initialization here
$sql = "SELECT * FROM products WHERE id = :id";
$stmt = $db->prepare($sql);
$stmt->execute(['id' => $product['product_id']]);
$product = $stmt->fetch(PDO::FETCH_OBJ);
$admin = $db->query('SELECT * FROM admins WHERE id = 1')->fetch(PDO::FETCH_OBJ);

?>

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="_next/static/css/ff8d6c6ab4a073db.css"/>
    <link rel="stylesheet" type="text/css" href="_next/static/css/454bf7671580d9b7.css"/>
    <link rel="stylesheet" type="text/css" href="_next/static/css/app.6228f064c108b5d46e18.css"/>
    <link rel="stylesheet" type="text/css" href="_next/static/css/font.6228f064c108b5d46e18.css"/>
    <script>
        var basket = <?= $basket_json ?>;
        console.log(basket);
    </script>
</head>

<div class="basket">
    <div class="basketHeader container">
        <a href="/">
            <div class="logo">
                <img src="catalog/view/assets/images/logos/karaca.png" alt="Karaca">
            </div>
        </a>
        <div class="account"></div>
        <div class="mobileBasketHeader">
            <a onclick="window.history.go(-1); return false;" class="item">
                <i class="krc-arrow2-left"></i>
            </a>
            <img src="catalog/view/assets/images/logos/krc-mini-icon.svg" alt="">
            <div class="item wishLinks">
                <a data-toggle="modal" data-target="#modalClearCart"><i class="krc-trash"></i></a>
            </div>
        </div>
    </div>
    <div class="basketContent">
        <div class="container">
            <div class="row basketRow">
                <div class="col-sm-12 col-lg-8 left">
                    <div id="related-cart-firsat"></div>
                    <div class="mobile-tabs">
                        <div class="row">
                            <div class="col-6 basket-items item active" data-type="basket-items">Sepetim <span
                                        class="count"><?= count($basket) ?></span></div>
                            <div class="col-6 favorites item" data-type="favorites">Favorilerim</div>
                        </div>
                    </div>

                    <div class="krc-alert wallet-alert">
                        <div class="icon">
                            <img src="https://static.karaca.com/catalog/view/assets/images/wallet/icons/info-icon.svg"
                                 alt="i">
                        </div>
                        <div class="text"> Sınırlı süredeki bu indirimi <strong>hemen</strong> sende yakala!</div>
                    </div>

                    <div class="head"><span>Sepetim (<?= count($basket) ?>)</span></div>
                    <?php
                    $toplamFiyat = 0;
                    foreach ($basket as $productItem):
                        $sql = "SELECT * FROM products WHERE id = :id";
                        $stmt = $db->prepare($sql);
                        $stmt->execute(['id' => $productItem['product_id']]);
                        $product = $stmt->fetch(PDO::FETCH_OBJ);
                        if ($product):
                            $toplamFiyat += $product->ProductPrice;
                            
                            $originalPrice = $product->ProductPrice;
                            $discountPercentage = 80;
                            $oldPrice = $originalPrice * (100 / (100 - $discountPercentage));
                            ?>
                            <div class="orderPreview">
                                <input type="hidden" id="coupon_use_status" value="">
                                <div class="un_promotion"></div>
                                <form name="cart" action="https://www.karaca.com/checkout/cart" method="post"
                                      enctype="multipart/form-data">
                                    <div class="d-flex flex-column basketProductWrap-outer">
                                        <div class="basketProductWrap basketProductWrap_0"
                                             data-product_id="<?= $product->id ?>" data-store_status="0">
                                            <a href="#" class="js-remove-product" data-id="<?= $product->id ?>"
                                               id="removecartproductAll-<?= $product->id ?>"
                                               data-track="track-removefromcart"></a>
                                            <div class="img">
                                                <a href="https://www.karaca.com/urun/<?= $product->Slug ?>">
                                                    <img src="assets/img/products/<?= $product->ImageURL ?>"
                                                         alt="<?= $product->ProductName ?>">
                                                </a>
                                            </div>
                                            <div class="product">
                                                <div class="detail">
                                                    <div class="left">
                                                        <div class="name">
                                                            <a href="#"><?= $product->ProductName ?></a>
                                                        </div>
                                                        <div class="orderDate" data-presales="0"
                                                             data-shipping_product_id="<?= $product->id ?>"
                                                             data-shipping_system="1"
                                                             data-shipping_text="3 iş günü içerisinde kargoda!">
                                                            3 iş günü içerisinde kargoda!
                                                        </div>
                                                        <div class="freeShip">Ücretsiz Kargo</div>
                                                        <div class="priceMobile">
                                                            <span class="basketItemoldPrice"><?= number_format($oldPrice, 2) ?> TL</span>
                                                            <span class="basketItemPrice"><?= number_format($product->ProductPrice, 2) ?> TL</span>
                                                        </div>
                                                    </div>
                                                    <div class="pl-4 right align-items-start">
                                                        <div class="count">
                                                            <a href="#" data-id="<?= $product->id ?>"
                                                               class="circle qty-removeCart js-remove-product"
                                                               id="removecartproduct2-<?= $product->id ?>"
                                                               data-track="track-removefromcart"><i
                                                                        class="krc-trash"></i></a>
                                                            <input type="number" id="spinner" class="number"
                                                                   name="quantity[<?= $product->id ?>]" value="1"
                                                                   min="1" step="1" max="99"
                                                                   product_id="<?= $product->id ?>"
                                                                   onchange="$('form[name=cart]').submit();"
                                                                   readonly="">
                                                        </div>
                                                        <div class="price">
                                                            <span class="basketItemoldPrice"><?= number_format($oldPrice, 2) ?> TL</span>
                                                            <span class="basketItemPrice"><?= number_format($product->ProductPrice, 2) ?> TL</span>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        <?php
                        endif;
                    endforeach;
                    ?>
                </div>
                <div class="summaryMain d-block d-sm-none">
                    <div class="pb-3 pl-3 font-weight-bold title">Sipariş Özeti</div>
                    <div class="summary-detail">
                        <div class="line summary-detail__wrapper " id="sub_total"
                             data-sub-total="<?= $toplamFiyat ?>"><span
                                    class="summary-detail__label">Ara Toplam</span><span
                                    class="summary-detail__price"><?= number_format($toplamFiyat, 2) ?></span>
                        </div>
                        <div class="line summary-detail__wrapper success" id="shipping" data-shipping="0"><span
                                    class="summary-detail__label">Ücretsiz Kargo</span><span
                                    class="summary-detail__price"
                                    style="color:#05b71d;">0.00 TL</span>
                        </div>
                        <div class="line summary-detail__wrapper " id="total" data-total="<?= $toplamFiyat ?>"><span
                                    class="summary-detail__label">Toplam</span><span
                                    class="summary-detail__price"><?= number_format($toplamFiyat, 2) ?> TL</span>
                        </div>
                    </div>
                </div>
                <div class="relatedWidgets d-block d-sm-none">
                    <div id="cart-related-reco-1"></div>
                    <div id="cart-related-reco-2"></div>
                    <div id="cart-related-reco-3"></div>
                    <div id="cart-related-reco-4"></div>
                    <div id="cart-related-reco-5"></div>
                </div>
                <div class="sticky-summary d-flex d-sm-none">
                    <div class="price">
                        <div class="right text-left" id="amountToBePaid"><span>Ödenecek Tutar</span>
                            <div class="price-merge"><strong id="cart-total-mobil"><?= number_format($toplamFiyat, 2) ?>
                                    TL</strong></div>
                        </div>
                    </div>
                    <div class="orderNextStep">
                        <form action="tamamla.php" method="get">
                            <button type="submit" class="krc-btn krc-btn-full setGift">Ödeme Adımına Geç</button>
                        </form>
                    </div>
                </div>
                <div class="modal fade modal_open_wishlistProductDelete" id="wishlistProductDelete" tabindex="-1"
                     role="dialog"
                     aria-labelledby="modal_wishlistProductDeleteLabel" aria-hidden="true">
                    <div class="modal-dialog modal- modal-dialog-centered" role="document">
                        <div class="modal-content">
                            <div class="modal-header"><span class="modal-title"
                                                            id="modal_wishlistProductDeleteLabel"><strong></strong></span>
                                <button type="button" class="close modalCloseCustom" data-dismiss="modal"
                                        aria-label="Close"><i
                                            class="krc-close-circle"></i></button>
                            </div>
                            <div class="modal-body">
                                <div class="modalBodyKrc"><span class="heart"><i class="krc-heart"></i></span><span
                                            class="title">Favorilerilerden Kaldır</span>
                                    <button type="button" class="close modalCloseCustom" data-dismiss="modal"
                                            aria-label="Close"><i
                                                class="krc-close-circle"></i></button>
                                    <span class="text">Ürün favorilerinizden kaldırılmıştır.</span></div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-sm-12 col-lg-4 d-none d-sm-block right">
                    <div class="orderSummary">
                        <div class="makemesticky">
                            <div class="head"><span>Sipariş Özeti</span></div>
                            <div class="summaryInfo">
                                <div class="line summary-detail__wrapper " id="sub_total"
                                     data-sub-total="<?= $toplamFiyat ?>">
                                    <span class="summary-detail__label">Ara Toplam</span><span
                                            class="summary-detail__price"> <?= number_format($toplamFiyat, 2) ?> TL</span>
                                </div>
                                <div class="line summary-detail__wrapper success" id="shipping" data-shipping="0">
                                    <span class="summary-detail__label">Ücretsiz Kargo</span><span
                                            class="summary-detail__price" style="color:#05b71d;"> 0.00 TL</span>
                                </div>
                                <div class="line summary-detail__wrapper " id="total" data-total="<?= $toplamFiyat ?>">
                                    <span class="summary-detail__label">Toplam</span><span
                                            class="summary-detail__price"> <?= number_format($toplamFiyat, 2) ?> TL</span>
                                </div>
                            </div>
                            <div class="orderNextStep">
                                <form action="tamamla.php" method="get">
                                    <button type="submit" class="krc-btn krc-btn-full setGift">Ödeme Adımına Geç
                                    </button>
                                </form>
                            </div>
                            <div class="basketInfoText text-center">
                                Sepetindeki ürünler sınırlı sayıda olup ödeme sırasında tükenebilir.
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    document.querySelectorAll('.js-remove-product').forEach(button => {
        button.addEventListener('click', function (e) {
            e.preventDefault();
            const productId = this.getAttribute('data-id'); // Silinmesi gereken ürünün ID'si

            fetch('remove_from_cart.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ product_id: productId })
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        //alert('Ürün sepetten başarıyla çıkarıldı.');
                        location.reload(); // Sayfayı yenile
                    } else {
                        alert('Bir hata oluştu.');
                    }
                })
                .catch(error => {
                    console.error('Hata:', error);
                });
        });
    });
</script>

<script>
document.querySelectorAll('.increase').forEach(button => {
    button.addEventListener('click', function (e) {
        e.preventDefault();
        const productId = this.getAttribute('data-id'); // Eklenmesi gereken ürünün ID'si

        fetch('add_to_cart.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ product_id: productId })
        })
        .then(response => response.json())
        .then(data => {
            console.log('Sunucu yanıtı:', data); // Sunucu yanıtını loglayalım
            if (data.success) {
                location.reload(); // Başarı mesajı olmadan sayfayı yenile
            } else {
                console.error('Bir hata oluştu:', data); // Hata mesajını buraya loglayalım
            }
        })
        .catch(error => {
            console.error('Fetch sırasında hata oluştu:', error); // Fetch hatasını logla
        });
    });
});


</script>