<?php
/*
 * Currency rate ko array mein convert karein.
 */
if (is_object($currencyrate) && method_exists($currencyrate, 'toArray')) {
    $currencyrate = $currencyrate->toArray();
} else {
    $currencyrate = (array) $currencyrate;
}

$session = $this->request->getSession();

$currency = $session->read('currency');
$currencySymbol = $session->read('currencysymbol');

if (empty($currencySymbol)) {
    $currencySymbol = 'Rs.';
}

/*
 * Currency rate available na hone par default rate 1 rahega.
 */
$currentCurrencyRate = 1;

if (
    isset($currencyrate[0]) &&
    isset($currencyrate[0][$currency])
) {
    $currentCurrencyRate = (float) $currencyrate[0][$currency];
}

/*
 * Coupon value ko safely read karein.
 */
$couponValue = 0;

if ($session->check('couponvalues')) {
    $couponValue = (float) $session->read('couponvalues');
}
?>

<div class="breadcrumb-img"></div>

<div class="breadcrumb">
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <ul>
                    <li>
                        <?php
                        echo $this->Html->link(
                            'Home',
                            [
                                'controller' => 'pages',
                                'action' => 'home'
                            ]
                        );
                        ?>
                    </li>
                    <li>Cart</li>
                </ul>
            </div>
        </div>
    </div>
</div>

<?php if (!$querycarts->isEmpty()) : ?>

    <?php $sum = 0; ?>

    <div class="cart-page">
        <div class="container">
            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                <div class="row">

                    <!-- Cart Products -->
                    <div class="col-md-8 col-sm-12 col-xs-12">

                        <?php foreach ($querycarts as $value) : ?>

                            <?php
                            $quantity = max(1, (int) $value['quantity']);
                            $price = (float) $value['price'];

                            $itemTotal = (int) round(
                                $quantity * $price * $currentCurrencyRate
                            );

                            $sum += $itemTotal;
                            ?>

                            <div class="cart-table">

                                <!-- Product Image -->
                                <div class="product-thumbnail">
                                    <?php
                                    echo $this->Html->link(
                                        $this->Html->image(
                                            $value['picture'],
                                            [
                                                'alt' => $value['name']
                                            ]
                                        ),
                                        [
                                            'controller' => 'details',
                                            'action' => 'detail',
                                            $value['url']
                                        ],
                                        [
                                            'escape' => false
                                        ]
                                    );
                                    ?>
                                </div>

                                <!-- Product Information -->
                                <div class="product-summary">

                                    <div class="product-name">
                                        <?php
                                        echo $this->Html->link(
                                            $value['name'],
                                            [
                                                'controller' => 'details',
                                                'action' => 'detail',
                                                $value['url']
                                            ]
                                        );
                                        ?>
                                    </div>

                                    <div class="product-quantity">

                                        <div class="product-price">
                                            <span class="amount">
                                                <?php
                                                echo h($currencySymbol);
                                                echo ' ';
                                                echo number_format($itemTotal, 0);
                                                ?>
                                            </span>
                                        </div>

                                        <div class="quantity">

                                            <?php
                                            /*
                                             * LegacyFormHelper mein hidden() method available nahi hai.
                                             * Isliye form helper sirf form open/close aur CSRF ke liye use ho raha hai,
                                             * jabki hidden fields aur buttons plain HTML mein hain.
                                             */
                                            echo $this->Form->create(
                                                'addtocart',
                                                [
                                                    'class' => 'quantity-form',
                                                    'method' => 'post',
                                                    'url' => [
                                                        'controller' => 'products',
                                                        'action' => 'updatecart'
                                                    ]
                                                ]
                                            );
                                            ?>

                                            <input
                                                type="hidden"
                                                name="cartrecord"
                                                value="<?php echo h($value['id']); ?>"
                                            >

                                            <input
                                                type="hidden"
                                                name="mykey"
                                                value="<?php echo h($value['mykey']); ?>"
                                            >

                                            <span class="minus-btn">
                                                <button
                                                    type="button"
                                                    class="quantity-button"
                                                    aria-label="Decrease quantity"
                                                >
                                                    <i class="icon icon-minus" aria-hidden="true">−</i>
                                                </button>
                                            </span>

                                            <input
                                                type="text"
                                                name="quantity"
                                                class="quantity-input"
                                                value="<?php echo $quantity; ?>"
                                                min="1"
                                                inputmode="numeric"
                                                readonly
                                            >

                                            <span class="plus-btn">
                                                <button
                                                    type="button"
                                                    class="quantity-button"
                                                    aria-label="Increase quantity"
                                                >
                                                    <i class="icon icon-plus" aria-hidden="true">+</i>
                                                </button>
                                            </span>

                                            <?php echo $this->Form->end(); ?>

                                        </div>
                                    </div>
                                </div>

                                <!-- Product Actions -->
                                <div class="product-action">

                                    <button
                                        type="button"
                                        class="add-to-wishlist"
                                        id="<?php echo h($value['mykey']); ?>"
                                    >
                                        <i class="icon icon-heart"></i>
                                        Save For Later
                                    </button>

                                    <?php
                                    echo $this->Html->link(
                                        '<i class="icon icon-trash"></i> Remove',
                                        [
                                            'controller' => 'products',
                                            'action' => 'cartremove',
                                            $value['id']
                                        ],
                                        [
                                            'escape' => false
                                        ]
                                    );
                                    ?>

                                </div>

                            </div>

                        <?php endforeach; ?>

                    </div>

                    <!-- Coupon and Cart Summary -->
                    <div class="col-md-4 col-sm-12 col-xs-12">

                        <!-- Coupon Form -->
                        <?php
                        echo $this->Form->create(
                            'register',
                            [
                                'class' => 'coupon-code',
                                'method' => 'post'
                            ]
                        );

                        echo $this->Form->control(
                            'coupon',
                            [
                                'type' => 'text',
                                'label' => false,
                                'placeholder' => 'Coupon Code',
                                'value' => $this->request->getData('coupon'),
                                'required' => true,
                                'autocomplete' => 'off'
                            ]
                        );
                        ?>

                        <button
                            class="submitbtn"
                            type="submit"
                            name="submit"
                            value="1"
                        >
                            Apply
                        </button>

                        <div class="clearfix"></div>

                        <?php
                        if (
                            $this->request->getData('submit') &&
                            !$session->check('couponcode')
                        ) :
                        ?>
                            <div class="validate-popup">
                                Invalid coupon
                            </div>
                        <?php endif; ?>

                        <?php echo $this->Form->end(); ?>

                        <?php
                        $shipping = 0;
                        $totalPayable = ($sum + $shipping) - $couponValue;

                        if ($totalPayable < 0) {
                            $totalPayable = 0;
                        }
                        ?>

                        <!-- Cart Summary -->
                        <div class="row">
                            <div class="col-md-12 col-sm-12 col-xs-12">

                                <div class="checkout-summary">

                                    <div class="title">
                                        Cart Detail
                                        <span>
                                            (<?php echo (int) $querycartstotal; ?>
                                            <?php
                                            echo ((int) $querycartstotal === 1)
                                                ? 'Item'
                                                : 'Items';
                                            ?>)
                                        </span>
                                    </div>

                                    <div class="price">
                                        <span>Cart Total</span>
                                        <span>
                                            <strong>
                                                <?php
                                                echo h($currencySymbol);
                                                echo ' ';
                                                echo number_format($sum, 0);
                                                ?>
                                            </strong>
                                        </span>
                                    </div>

                                    <?php if ($session->check('couponcode')) : ?>

                                        <div class="price">
                                            <span>Discount</span>
                                            <span>
                                                <strong>
                                                    -<?php
                                                    echo h($currencySymbol);
                                                    echo ' ';
                                                    echo number_format($couponValue, 0);
                                                    ?>
                                                </strong>
                                            </span>
                                        </div>

                                    <?php endif; ?>

                                    <div class="price">
                                        <span>Shipping</span>
                                        <span><strong>Free</strong></span>
                                    </div>

                                    <div class="subtotal">
                                        <span>Total Payable</span>
                                        <span>
                                            <strong>
                                                <?php
                                                echo h($currencySymbol);
                                                echo ' ';
                                                echo number_format($totalPayable, 0);
                                                ?>
                                            </strong>
                                        </span>
                                    </div>

                                    <div class="clearfix"></div>

                                    <div class="cartcheckout">
                                        <?php
                                        echo $this->Html->link(
                                            'Place Order',
                                            [
                                                'controller' => 'checkouts',
                                                'action' => 'deliveryaddress'
                                            ]
                                        );
                                        ?>
                                    </div>

                                </div>
                            </div>
                        </div>

                    </div>

                </div>
            </div>
        </div>
    </div>

<?php else : ?>

    <div class="notfound">
        <h2>There are no items in your Shopping Cart</h2>
    </div>

<?php endif; ?>

<script>
$(document).ready(function () {

    /*
     * Product quantity increase karein aur related form submit karein.
     */
    $(document).on('click', '.plus-btn', function (event) {
        event.preventDefault();

        var form = $(this).closest('.quantity-form');
        var input = form.find('.quantity-input');
        var currentQuantity = parseInt(input.val(), 10);

        if (isNaN(currentQuantity) || currentQuantity < 1) {
            currentQuantity = 1;
        }

        input.val(currentQuantity + 1);
        form.find('button').prop('disabled', true);

        if (form.length && form[0]) {
            form[0].submit();
        }
    });

    /*
     * Quantity ko minimum 1 tak decrease karein.
     */
    $(document).on('click', '.minus-btn', function (event) {
        event.preventDefault();

        var form = $(this).closest('.quantity-form');
        var input = form.find('.quantity-input');
        var currentQuantity = parseInt(input.val(), 10);

        if (isNaN(currentQuantity) || currentQuantity <= 1) {
            input.val(1);
            return false;
        }

        input.val(currentQuantity - 1);
        form.find('button').prop('disabled', true);

        if (form.length && form[0]) {
            form[0].submit();
        }
    });

});
</script>
