<?php
include "inc/app-top-member.php";

$cart_list = $eagro->getCartListByMerchant($_SESSION["member_id"]);
$cart_array = json_decode($cart_list, true);

$address_result = $eagro->getStateList();
$address_array = json_decode($address_result, true);


$checking_cart_product = $eagro->checkingUserCart($_SESSION['member_id']);
$result_cart_product = json_decode($checking_cart_product, true);

if ($result_cart_product['valid'] == true) {
    header("Refresh:0");
}

?>
<!DOCTYPE html>
<html>
<head>
    <title>E-Agro Cart</title>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet"/>

    <?php include "inc/head.php"; ?>
    <style type="text/css">
    	@media only screen and (max-width: 479px){
          body {
              padding-top: 350px;
          }
        }

        .discount-coupon button:hover {
            background-color: #5d8801 !important;
        }

        .calculate-shipping input[type="button"]:hover {
            background-color: #5d8801 !important;
        }

        .modal-footer button:hover {
            background-color: #5d8801 !important;
        }

        .modal-footer .close button:hover {
            background-color: #80bb01 !important;
            color: white !important;
        }

        .font-voucher {
            margin-top: 20px;
            font-size: 14px;
            font-weight: 500;
            line-height: 23px;
            color: #222222;
        }

        .select2-container, .select2-dropdown, .select2-search, .select2-results {
            -webkit-transition: none !important;
            -moz-transition: none !important;
            -ms-transition: none !important;
            -o-transition: none !important;
            transition: none !important;
        }

        .no-show {
            display: none;
        }
    </style>
</head>
<body>
<header>
    <?php include "inc/header.php"; ?>
</header>
<script>

    $(document).ready(function () {
        $('.select-d2d').select2();


        $('body').on('change', '.select-d2d', function () {

            var product_id = $(this).attr('data-product-id');
            var selected_area = $(this).val();
            // alert(selected_area);
            var member_id = '<?php echo $_SESSION['member_id']; ?>';

            var formData = {
                'action': 'updateD2dAreaInCart',
                'product_id': product_id,
                'area_id': selected_area,
                'member_id': member_id
            }

            $.ajax({
                type: 'post',
                url: 'action.php',
                data: formData,
                success: function (result) {

                    var result_obj = JSON.parse(result);

                    if (result_obj.valid) {
                        location.reload();
                    }
                }
            })
        })
    })

    $(document).ready(function () {
        $('.select-bs').select2();


        $('body').on('change', '.select-bs', function () {

            var product_id = $(this).attr('data-product-id');
            var selected_price = $(this).val();
            var member_id = '<?php echo $_SESSION['member_id']; ?>';
            // alert(selected_price);

            var formData = {
                'action': 'updateBajaServiceInCart',
                'product_id': product_id,
                'price': selected_price,
                'member_id': member_id
            }

            $.ajax({
                type: 'post',
                url: 'action.php',
                data: formData,
                success: function (result) {

                    var result_obj = JSON.parse(result);

                    if (result_obj.valid) {
                        location.reload();
                    }
                }
            })
        })
    })

    function quantity(product_id, buttonId) {

        var cart_quantity = $("#quantity" + buttonId).val();
        var member_id = $("#member-id").val();


        var formData = {
            "action": "updateCartQuantity",
            "product_id": product_id,
            "cart_quantity": cart_quantity,
            "member_id": member_id,
        };

        $.ajax({
            type: 'post',
            url: 'action.php',
            data: formData,
            success: function (result) {

                var result_obj = JSON.parse(result);

                if (result_obj.valid) {
                    location.reload();
                } else {
                    document.getElementById('quantity' + buttonId).value = parseFloat(cart_quantity - 1);
                    swal({
                        type: 'error',
                        title: 'Oops..',
                        html: result_obj.msg,
                    });

                }
            }
        })

    }

    function remove(product_id, member_id) {
        var product_id = product_id;
        var member_id = member_id;

        var FormData = {
            "product_id": product_id,
            "member_id": member_id,

        };
        $.ajax({
            type: 'POST',
            url: 'classes/remove-item.php',
            data: FormData,
            success: function (result) {
                console.log(result);
                if (result == 1) {

                    // swal({
                    // 	type: 'success',
                    // 	title: 'success!',
                    // 	text: "Successfully"
                    // });
                    location.reload();
                } else if (result == 2) {
                    swal({
                        type: 'error',
                        title: 'Oops...',
                        text: "Please try again."
                    });
                }
            }
        });
    }

    function applyVoucher(merchant_id) {
        var member_id = $("#member-id").val();
        var language = $("#language").val();
        // alert(language);
        var voucher = $("#voucher" + merchant_id).val();
        if (voucher == "" || voucher == null) {
            if (language == 1) {
                swal({
                    type: 'error',
                    title: 'Maaf..',
                    text: 'Sila isi baucar kod untuk pengesahan'
                })
            } else {
                swal({
                    type: 'error',
                    title: 'Oops..',
                    html: "Please enter voucher to apply."
                });
            }

        } else {

            var formData = {
                "action": "applyVoucher",
                "member_id": member_id,
                "merchant_id": merchant_id,
                "voucher": voucher
            };


            $.ajax({
                type: 'post',
                url: 'action.php',
                data: formData,
                success: function (result) {
                    var result_obj = JSON.parse(result);
                    if (language == 1) {
                        if (result_obj.valid) {
                            swal({
                                type: 'success',
                                title: 'Berjaya!',
                                text: 'Baucar telah berjaya di sahkan'
                            }).then(function () {
                                location.reload();
                            })
                        } else {

                            swal({
                                type: 'error',
                                title: 'Maaf..',
                                text: 'Baucar tidak sah'
                            })


                        }
                    } else {
                        if (result_obj.valid) {
                            swal({
                                type: 'success',
                                title: 'Looks Great!',
                                html: result_obj.msg
                            }).then(function () {
                                location.reload();
                            })
                        } else {

                            swal({
                                type: 'error',
                                title: 'Oops..',
                                html: result_obj.msg
                            })


                        }
                    }

                }
            })
        }
    }

    function deleteVoucher(merchant_id) {
        var member_id = $("#member-id").val();
        var language = $("#language").val();

        var formData = {
            "action": "deleteVoucherInCart",
            "merchant_id": merchant_id,
            "member_id": member_id
        };

        $.ajax({
            type: 'post',
            url: 'action.php',
            data: formData,
            success: function (result) {
                var result_obj = JSON.parse(result);
                if (language == 1) {
                    if (result_obj.valid) {

                        swal({
                            type: 'success',
                            title: 'Berjaya!',
                            text: 'Baucar telah berjaya dibuang'
                        }).then(function () {
                            location.reload();
                        })
                    } else {

                        swal({
                            type: 'error',
                            title: 'Maaf..',
                            text: 'Tidak berjaya!'
                        })

                    }
                } else {
                    if (result_obj.valid) {

                        swal({
                            type: 'success',
                            title: 'Looks Great!',
                            html: result_obj.msg
                        }).then(function () {
                            location.reload();
                        })
                    } else {

                        swal({
                            type: 'error',
                            title: 'Oops..',
                            html: result_obj.msg
                        })

                    }
                }


            }
        })
    }

    function checkout() {
        var member_id = $("#member-id").val();
        var language = $("#language").val();

        var validateAll = [];

        $('.select-d2d').each(function () {
            if ($(this).val() == null || $(this).val() == "") {
                if (language == 1) {
                    swal({
                        type: 'error',
                        title: 'Maaf..',
                        html: 'Sila pilih servis!'
                    });
                } else {
                    swal({
                        type: 'error',
                        title: 'Oops..',
                        html: 'Please select the service!'
                    });
                }


                validateAll.push(false);

            } else {
                validateAll.push(true);
            }
        })

        var finalValidationStatus = validateAll.includes(false);

        if (!finalValidationStatus) {
            $.ajax({
                type: 'post',
                url: 'action.php',
                data: {"action": "checkingStockCheckout", "member_id": member_id},
                success: function (result) {
                    var result_obj = JSON.parse(result);

                    if (result_obj.valid) {
                        var random = Math.floor(100000 + Math.random() * 900000);
                        location.href = "checkout.php?order_id=" + random;
                    } else {
                        if (language == 1) {
                            swal({
                                type: 'error',
                                title: 'Maaf..',
                                text: 'Anda mempunyai satu atau lebih item yang telah kehabisan stok.'
                            })
                        } else {
                            swal({
                                type: 'error',
                                title: 'Oops..',
                                html: result_obj.msg
                            })
                        }

                    }
                }
            })
        }
    }

    function addAddressMember() {
        var checking = checking_address_required();
        var addressFullName = $("#addFullName").val();
        var addAddress = $("#addAddress").val();
        var city = $("#addCity").val();
        var postcode = $("#addPostcode").val();
        var state = $("#addState").val();
        var phoneNumber = $("#addPhone").val();
        var member_id = $("#member-id").val();


        if (checking) {
            var formData = {
                "action": "addAddressOnCart",
                "addressFullName": addressFullName,
                "addAddress": addAddress,
                "city": city,
                "postcode": postcode,
                "state": state,
                "phoneNumber": phoneNumber,
                "member_id": member_id
            }
            $.ajax({
                type: 'post',
                url: 'action.php',
                data: formData,
                success: function (result) {
                    var result_obj = JSON.parse(result);

                    if (result_obj.valid) {
                        swal({
                            type: 'success',
                            title: 'Looks Great!',
                            html: result_obj.msg
                        }).then(function () {
                            location.reload();
                        })
                    } else {
                        swal({
                            type: 'error',
                            title: 'Oops..',
                            html: result_obj.msg
                        })
                    }
                }
            })
        } else {
            swal({
                type: 'error',
                title: 'Oops..',
                html: 'Please key in all the information.'
            })
        }
    }

    function checking_address_required() {
        var checking = '';

        $('.required').each(function () {
            if ($(this).val() == "" || $(this).val() == null) {
                return checking = false;
            } else {
                return checking = true;
            }
        })
        return checking;
    }

    //Update door to door service status
    $(document).ready(function () {
        $('.checkD2d').click(function () {
            var member_id = $("#member-id").val();
            var product_id = $(this).attr('id');
            if ($(this).prop("checked") == true) {
                var checkedValue = 1;
            } else {
                var checkedValue = 2;
            }

            var formData = {
                "action": "updateCheckboxD2d",
                "member_id": member_id,
                "product_id": product_id,
                "checkedValue": checkedValue
            };

            $.ajax({
                type: 'post',
                url: 'action.php',
                data: formData,
                success: function (result) {
                    var result_obj = JSON.parse(result);

                    if (result_obj.valid) {
                        location.reload();
                    }
                }
            })
        });


        //Disabled when click enter will auto submit on form
        $('form input').on('keypress', function (e) {
            return e.which !== 13;
        });
    })
</script>
<div class="breadcrumb-area mb-50">
    <div class="container">
        <div class="row">
            <div class="col">
                <div class="breadcrumb-container">
                    <ul>
                        <li><a href="index.php"><i class="fa fa-home"></i> <?php echo change("menu"); ?></a></li>
                        <li class="active"><?php echo change("menu5"); ?></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<!--=====  End of breadcrumb area  ======-->


<!--=============================================
=            Cart page content         =
=============================================-->

<div class="page-section section mb-50">
    <div class="container">
        <div class="row">
            <div class="col-12">
                <input type="hidden" id="language" value="<?php echo $_SESSION["language"]; ?>">

                <!--=======  cart table  =======-->
                <!-- <p style="color:red"> * <?php echo change("note"); ?> </p>
                        <br> -->
                <?php
                if ($cart_array["valid"]) {
                    for ($c = 0; $c < count($cart_array["data_merchant"]); $c++) {
                        ?>
                        <h5><B><?php echo $cart_array["data_merchant"][$c]["company_name"]; ?></B></h5>
                        <div class="cart-table table-responsive mb-40">
                            <table class="table">
                                <thead>
                                <tr>
                                    <th class="pro-thumbnail"><?php echo change("image"); ?></th>
                                    <th class="pro-title"><?php echo change("product"); ?></th>
                                    <th class="pro-price"><?php echo change("price"); ?></th>
                                    <th class="pro-quantity"><?php echo change("quantity"); ?></th>
                                    <th class="pro-subtotal"><?php echo change("total"); ?></th>
                                    <th class="pro-subtotal"><?php echo change("service"); ?></th>
                                    <th class="pro-remove"><?php echo change("remove"); ?></th>
                                </tr>
                                </thead>
                                <tbody>
                                <?php
                                $result_cart_product = $eagro->getCartProduct($cart_array["data_merchant"][$c]["merchant_id"], $_SESSION["member_id"]);
                                $array_cart_product = json_decode($result_cart_product, true);

                                for ($p = 0; $p < count($array_cart_product["data_product"]); $p++) {

                                    ?>
                                    <input type="hidden" id="member-id" value="<?php echo $_SESSION["member_id"]; ?>">
                                    <input type="hidden" id="product-id"
                                           value="<?php echo $array_cart_product["data_product"][$p]["product_id"]; ?>">
                                    <tr>
                                        <td class="pro-thumbnail">

                                            <?php

                                            if ($array_cart_product['data_product'][$p]['item_category'] == 0) {

                                                ?>
                                                <img src="merchant/image/product/<?php echo $array_cart_product["data_product"][$p]["product_path"]; ?>"
                                                     class="img-fluid" alt="Product" style="height:120px;">
                                                <?php
                                            } else {
                                                if ($array_cart_product['data_product'][$p]['product_category'] == 1) {
                                                    ?>
                                                    <img src="contractor/image/con.jpg" class="img-fluid" alt="Product"
                                                         style="height:120px;">
                                                    <?php
                                                } else if ($array_cart_product['data_product'][$p]['product_category'] == 2) {

                                                    ?>
                                                    <img src="contractor/image/con3.jpeg" class="img-fluid"
                                                         alt="Product" style="height:120px;">
                                                    <?php

                                                } else if ($array_cart_product['data_product'][$p]['product_category'] == 3) {
                                                    ?>
                                                    <img src="contractor/image/replanting.jpg" class="img-fluid"
                                                         alt="Product" style="height:120px;">
                                                    <?php
                                                }


                                            }

                                            ?>
                                        </td>
                                        <td class="pro-title">
                                            <?php echo $array_cart_product["data_product"][$p]["product_name"]; ?><?php if ($array_cart_product["data_product"][$p]["payment_method"] == 0 || $array_cart_product["data_product"][$p]["payment_method"] == 2) {
                                                echo "<span style='color:red;'> * </span>";
                                            } ?>
                                        </td>
                                        <td class="pro-price">
                                            <span>RM<?php echo number_format($array_cart_product["data_product"][$p]["product_price"], 2, '.', ','); ?></span>
                                        </td>
                                        <td class="pro-quantity">
                                            <div class="pro-qty"
                                                 id="<?php echo $array_cart_product["data_product"][$p]["product_id"]; ?>"
                                                 onclick="quantity(<?php echo $array_cart_product["data_product"][$p]["product_id"]; ?>,this.id);">
                                                <input type="text" readonly
                                                       id="quantity<?php echo $array_cart_product["data_product"][$p]["product_id"]; ?>"
                                                       value="<?php echo $array_cart_product["data_product"][$p]["cart_quantity"]; ?>">
                                            </div>
                                        </td>
                                        <td class="pro-subtotal">
                                                        <span>
                                                            <?php echo "RM" . $array_cart_product["data_product"][$p]["price"]; ?>
                                                        </span>
                                        </td>
                                        <td>
                                            <select class="select-d2d required-d2d"
                                                    data-product-id="<?php echo $array_cart_product["data_product"][$p]["product_id"]; ?>">
                                                <!-- <option disabled selected> - <?php echo change("d2ds"); ?> -</option> -->
                                                <?php
                                                if ($array_cart_product['data_product'][$p]['item_category'] == 0) {
                                                    ?>
                                                    <option value="1" selected <?php echo($array_cart_product['data_product'][$p]['cart_d2d'] == 1 ? 'selected' : 'selected'); ?>>
                                                        Self Pickup (RM0.00)
                                                    </option>
                                                    <?php
                                                }
                                                ?>
                                                <?php
                                                $get_d2d_area = $eagro->get_d2d_area($array_cart_product["data_product"][$p]["product_id"]);
                                                $array_d2d_area = json_decode($get_d2d_area, true);

                                                for ($a = 0; $a < count($array_d2d_area['data']); $a++) {
                                                    ?>
                                                    <option <?php echo($array_cart_product['data_product'][$p]['cart_d2d'] == $array_d2d_area['data'][$a]['area_id'] ? 'selected' : null); ?>
                                                            value="<?php echo $array_d2d_area['data'][$a]['area_id']; ?>"><?php echo $array_d2d_area['data'][$a]['malaysia_cities'] . ' (RM' . number_format($array_d2d_area['data'][$a]['area_price'], 2, '.', '') . ')'; ?></option>
                                                    <?php
                                                }
                                                ?>
                                            </select>

                                            <br><br>

                                            <?php if ($array_cart_product["data_product"][$p]["product_fertilizer_service"] == 1 && $array_cart_product["data_product"][$p]["cart_quantity"] > 39) { ?>
                                                <select class="select-bs required-bs"
                                                        data-product-id="<?php echo $array_cart_product["data_product"][$p]["product_id"]; ?>">
                                                    <option disabled selected> -- <?php echo change("baja"); ?>--
                                                    </option>
                                                    <option <?php echo($array_cart_product['data_product'][$p]['cart_baja_service'] == 0 ? 'selected' : null); ?>
                                                            value="0">No (RM 0.00)
                                                    </option>

                                                    <option <?php echo($array_cart_product['data_product'][$p]['cart_baja_service'] == $array_cart_product["data_product"][$p]["product_fertilizer_price"] ? 'selected' : null); ?>
                                                            value="<?php echo $array_cart_product["data_product"][$p]["product_fertilizer_price"]; ?>">
                                                        Yes
                                                        (RM <?php echo number_format($array_cart_product["data_product"][$p]["product_fertilizer_price"], 2, '.', '') ?>
                                                        )
                                                    </option>


                                                </select>
                                            <?php } ?>


                                        </td>
                                        <td class="pro-remove">
                                            <a>
                                                <i class="fa fa-trash-o"
                                                   onclick="remove(<?php echo $array_cart_product["data_product"][$p]["product_id"]; ?>,<?php echo $_SESSION["member_id"]; ?>);"></i>
                                            </a>
                                        </td>
                                    </tr>
                                    <?php


                                    $result_subtotal_by_merchant = $eagro->getSubTotalByMerchant($_SESSION["member_id"], $array_cart_product["data_product"][$p]["merchant_id"]);
                                    $array_subtotal_by_merchant = json_decode($result_subtotal_by_merchant, true);
                                    // print_r($array_subtotal_by_merchant);
                                    $merchant_id = $array_cart_product["data_product"][$p]["merchant_id"];


                                }
                                ?>
                                <tr>

                                </tr>
                                </tbody>

                            </table>

                            <div class="row" style="margin-left: 0px;margin-right: 0px;">
                                <div class="col-lg-6 col-12 mt-5">
                                    <?php
                                    if ($cart_array["data_merchant"][$c]["boolean_voucher"] == 2) {
                                        ?>
                                        <div class="discount-coupon">
                                            <p class="font-voucher"><?php echo change("voucher"); ?></p>

                                            <div class="row">
                                                <div class="col-md-6 col-12 mb-25">
                                                    <input type="text" id="voucher<?php echo $merchant_id; ?>"
                                                           placeholder="<?php echo change("voucherc"); ?>"
                                                           style="width: 100%;border-radius: 50px;height: 36px;border: 1px solid #999999;line-height: 24px;padding: 5px 20px;color: #666666;background-color: transparent;">
                                                </div>
                                                <div class="col-md-6 col-12 mb-25">

                                                    <button onclick="applyVoucher(this.id);"
                                                            id="<?php echo $merchant_id; ?>"
                                                            style="font-weight: 400;text-transform: uppercase;color: #ffffff;background-color: #80bb01;border-color: #80bb01;width: 140px;border-radius: 50px; height: 36px;padding: 5px 20px;line-height: 24px;    border: 1px solid #999999"><?php echo change("apply"); ?></button>

                                                </div>
                                            </div>

                                        </div>
                                        <?php
                                    } else {
                                        ?>
                                        <div class="discount-coupon">
                                            <p class="font-voucher"><?php echo change("voucher"); ?></p>

                                            <div class="row">
                                                <div class="col-md-6 col-12 mb-25">
                                                    <button onclick="deleteVoucher(this.id);"
                                                            id="<?php echo $merchant_id; ?>"
                                                            style="font-weight: 400;text-transform: uppercase;color: #ffffff;background-color: #80bb01;border-color: #80bb01;width:auto;border-radius: 50px; height: 36px;padding: 5px 20px;line-height: 24px;    border: 1px solid #999999"><?php echo change("remove2"); ?></button>
                                                </div>
                                            </div>

                                        </div>
                                        <?php
                                    }
                                    ?>
                                </div>
                                <div class="col-lg-6 col-12 d-flex mt-20">
                                    <div class="cart-summary">
                                        <div class="cart-summary-wrap">

                                            <p><?php echo change("subtotal"); ?>
                                                <span>RM<?php echo $array_subtotal_by_merchant["subTotal"]; ?></span>
                                            </p>
                                            <?php
                                            $style = 'style="display:none;"';
                                            ?>
                                            <p <?php if ($cart_array["data_merchant"][$c]["boolean_voucher"] == 2) {
                                                echo $style;
                                            } ?>>Voucher - <?php echo $array_subtotal_by_merchant["voucher_code"]; ?>
                                                <span>
                                                            - RM <?php echo $array_subtotal_by_merchant["discount_amount"]; ?>
                                                        </span>
                                            </p>
                                            <p><?php echo change("d2ds"); ?>
                                                <span>RM<?php echo $array_subtotal_by_merchant["d2dPrice"]; ?></span>
                                            </p>
                                            <?php if ($array_subtotal_by_merchant["bajaService"] != 0) { ?>
                                                <p><?php echo change("baja"); ?>
                                                    <span>RM<?php echo $array_subtotal_by_merchant["bajaService"]; ?></span>
                                                </p>
                                            <?php } ?>

                                            <p>
                                                <?php echo change("grandTotal"); ?>
                                                <span>
                                                            RM

                                                            <?php echo $array_subtotal_by_merchant["orderTotal"]; ?>
                                                        </span>
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php
                    }
                } else {
                    echo $cart_array["msg"];
                }

                ?>


                <!--=======  End of cart table  =======-->
                <div class="row">
                    <?php

                    if ($array_product["valid"]) {
                        ?>
                        <div class="col-lg-6 col-12">

                        </div>
                        <div class="col-lg-6 col-12 d-flex">
                            <!--=======  Cart summery  =======-->


                            <div class="cart-summary">
                                <div class="cart-summary-wrap">
                                    <h4 style="text-decoration: none;"><?php echo change("summary"); ?></h4>
                                    <h2><?php echo change("orderTotal"); ?> <span>
                                        RM
                                        <?php
                                        $result_cart_summary = $eagro->getCartSummaryCheckout($_SESSION["member_id"]);
                                        $array_cart_summary = json_decode($result_cart_summary, true);

                                        echo $array_cart_summary["grand_total"];
                                        ?>
                                    </span></h2>
                                </div>

                                <div class="cart-summary-button">
                                    <button class="checkout-btn"
                                            onclick="checkout();"><?php echo change("checkout"); ?></button>
                                    <!-- <button class="update-btn" onclick="location.reload();">Update Cart</button> -->
                                </div>
                            </div>

                            <!--=======  End of Cart summery  =======-->

                        </div>
                        <?php
                    }
                    ?>

                </div>

            </div>
        </div>
    </div>
</div>
</body>
<?php include "inc/inc-js.php"; ?>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>
<footer>
    <?php include "inc/footer.php"; ?>
</footer>

</html>
