<?php
$tipsConfig = config('tips');
$appLocale = env('APP_LOCALE');
if ($appLocale == "") {
    $appLocale = "us";
}
$tips = [];
if (isset($tipsConfig[$appLocale])) {
    $tips = $tipsConfig[$appLocale];
} else if (isset($tipsConfig['default'])) {
    $tips = $tipsConfig['default'];
}
$localeFinish = env('APP_LOCALE');
$criteoLocale = 'US';
if ($localeFinish) {
    $criteoLocale = strtoupper($localeFinish);
    $localeFinish = "/" . $localeFinish;

}
if (isset($order) && isset($order['id'])) {
    \Log::useDailyFiles(storage_path() . '/logs/view-finish.log');
    \Log::info("Viewing finished start - locale: " . $localeFinish . " order: " . $order['id']);
}
?>
@extends('layouts.master')

@section('css')
<link rel="stylesheet" data-name="FinishCss" href="{{ asset('modules/cart/css/finish-css.css') }}?v={{ config('sa.version') }}">
<link rel="stylesheet" data-name="ecardPopup" href="{{ asset('modules/cart/css/e-card-gift.css') }}?v={{ config('sa.version') }}">
@endsection

@section('main')
    @php
        $profit = null;
        $profitAfterChange = 0;
        $discount = 0;
        $discountAfterChange = 0;
        $currencyConvert = env('CURRENCY_UNIT','USD');
        $shippingDeduction = 0;
        if (isset($order['profit'])) {
            $profitDeduction = config('cart::sa.profitDeduction', 0);
            if ($profitDeduction > 0){
                $profit = $order['profit'] - ($order['amount'] * $profitDeduction);
            }else{
                $profit = $order['profit'];
            }
            $profitShippingDeduction = config('cart::sa.profitShippingDeduction', 0);
            if ($profitShippingDeduction > 0){
                $categoryCount = 1;
                if (isset($itemCategories) && is_array($itemCategories)){
                    $categoryCount = count($itemCategories);
                }
                $shippingDeduction = ($profitShippingDeduction * $categoryCount);
                $profit = $profit - $shippingDeduction;
            }
            if (isset($order['total_fee_cost'])){
                $profit = $profit - ($order['total_fee_cost'] * 0.08);
            }
            if (isset($order['other_fee'])){
                $profit = $profit - $order['other_fee'];
            }
             if (isset($order['tax'])){
                $profit = $profit - $order['tax'];
            }
             if (isset($order['offsite_ads_value'])){
                $profit = $profit + $order['offsite_ads_value'];
            }
            $profitConvert = convertPriceWithCurrency($profit,'VND',['orderId' => $order['id']]);
            if (!empty($profitConvert)){
                $profitAfterChange = $profitConvert;
                $currencyConvert = 'VND';
            }else{
                $profitAfterChange = $profit;
                $currencyConvert = env('CURRENCY_UNIT','USD');
            }
//            $precision = 2;
//            if (env('APP_LOCALE') == 'jp') {
//                $precision = 0;
//            }
//            \Log::info("Viewing finished end - locale before roundUp profit: " . $localeFinish . " order: " . $order['id'] . " profit: " . $profit);
//            $offset = 0.5;
//            $offset /= pow(10, $precision);
//            $profit = round($profit + $offset, $precision, PHP_ROUND_HALF_DOWN);
//            \Log::info("Viewing finished end - locale after roundUp profit: " . $localeFinish . " order: " . $order['id'] . " profit: " . $profit);
        }
        if (!empty($order['discount'])){
            $discount = $order['discount'];
            $discountAfterChange = convertPriceWithCurrency($discount,'VND');
        }
    $cjAmount = $order['amount'] -  $order['shipping_fee'] - $order['other_fee'] - $order['tips'];
    @endphp
    <div class="container-indent flex-box flex-w" id="cart-module-content">
        <div class="site-w">
            <nav aria-label="Breadcrumb">
                <ol class="checkout-breadcrumb breadcrumb--center" role="list">
                    <li class="breadcrumb__item breadcrumb__item--completed">
                        <span class="breadcrumb__text">{{ __('Cart') }}</span>
                        <small class="active"></small>
                    </li>
                    <li class="breadcrumb__item breadcrumb__item--completed">
                        <span class="breadcrumb__text">{{ __('Order Information') }}</span>
                        <small class="active"></small>
                    </li>
                    <li class="breadcrumb__item breadcrumb__item--current" aria-current="step">
                        <span class="breadcrumb__text">{{ __('Complete') }}</span>
                    </li>
                </ol>
            </nav>
        </div>
        <section class="js-confirm-page site-w">
            <div class="tshirt flex-b align-c">
                <img src="{{ getOption('general.successful_payment_img_url', asset('modules/cart/images/successful.png')) }}" alt="{{ __('Order Successful')}}">
                @if (isset($order['payment_type']) && $order['payment_type'] == 'RESERVE')
                    <div class="thanksMsg">
                        <?php $thanksMsg = 'Thank you for your purchase at %s'; ?>
                        <?php  $orderNo = 'Order no#%s'; ?>
                        <h1 class="finish-thank-you flex-b align-c">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check2-circle" viewBox="0 0 16 16">
                                <path d="M2.5 8a5.5 5.5 0 0 1 8.25-4.764.5.5 0 0 0 .5-.866A6.5 6.5 0 1 0 14.5 8a.5.5 0 0 0-1 0 5.5 5.5 0 1 1-11 0z"/>
                                <path d="M15.354 3.354a.5.5 0 0 0-.708-.708L8 9.293 5.354 6.646a.5.5 0 1 0-.708.708l3 3a.5.5 0 0 0 .708 0l7-7z"/>
                            </svg>
                            <span>{{ formatString(__($thanksMsg), getOption('general.store_name')) }}</span>
                        </h1>
                        <p class="finish-message">
                            {{ __("We've received your reserved order")}}. {{ __("You'll receive a confirmation email shortly to") }} <span class="finish-mail"> {{formatString($customerOrder['email'])}}</span>
                        </p>
                        <div class="your-order-code flex-b align-c">
                            <span class="finish-number-text">{{ __('Your order number is') }}:</span>
                            <span class="finish-number"> {{ formatString($order['code']) }}</span>
                        </div>
                        <p>
                            {{ __('Our staff will contact to assist you with the payment issue as soon as possible. Orders will be processed once you have completed your payment.') }}
                        </p>
                        <div class="finish-note">
                            {{ __('Note') }}: {{ __('If you do not receive notifications, they were likely mistaken for spam') }}. <br>{{ __('So, please check your Junk Mail / Spam folder') }}.
                        </div>
                        @view('checkout-finish-extends')
                        <div class="button-contain">
                            <a href="{{ route('home') }}" class="btn">{{ __('Continue shopping') }}</a>
                        </div>
                    </div>
                @else
                    <div class="thanksMsg">
                        <?php $thanksMsg = 'Thank you for your purchase at %s'; ?>
                        <?php  $orderNo = 'Order no#%s'; ?>
                        <h1 class="finish-thank-you flex-b align-c">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check2-circle" viewBox="0 0 16 16">
                                <path d="M2.5 8a5.5 5.5 0 0 1 8.25-4.764.5.5 0 0 0 .5-.866A6.5 6.5 0 1 0 14.5 8a.5.5 0 0 0-1 0 5.5 5.5 0 1 1-11 0z"/>
                                <path d="M15.354 3.354a.5.5 0 0 0-.708-.708L8 9.293 5.354 6.646a.5.5 0 1 0-.708.708l3 3a.5.5 0 0 0 .708 0l7-7z"/>
                            </svg>
                            <span>{{ formatString(__($thanksMsg), getOption('general.store_name')) }}</span>
                        </h1>
                        <p class="finish-message">
                            {{ __("We've received your order")}}. {{ __("You'll receive a confirmation email shortly to") }} <span class="finish-mail"> {{formatString($customerOrder['email'])}}</span>
                        </p>
                        <div class="your-order-code flex-b align-c">
                            <span class="finish-number-text">{{ __('Your order number is') }}:</span>
                            <span class="finish-number"> {{ formatString($order['code']) }}</span>
                        </div>
                        <p>
                            <?php
                            $trackOrderText = formatString(__('You can always track your order %s'), '<a class="track-order-link" href="' . clroute('/track-order?') . 'email=' . $customerOrder['email'] . '&order-code=' . $order['code'] .'">' . formatString(__('here')) .'</a>');
                            echo $trackOrderText;
                            ?>
                        </p>
                        @if (isset($order['payment_type']) && $order['payment_type'] == 'RESERVE' && getOption("reserve_note"))
                        <div class="finish-note" style="margin-bottom: 17px;">
                            {{ __(getOption("reserve_note")) }}
                        </div>
                        @endif
                        <div class="finish-note">
                            {{ __('Note') }}: {{ __('If you do not receive notifications, they were likely mistaken for spam') }}. <br>{{ __('So, please check your Junk Mail / Spam folder') }}.
                        </div>
                        @view('checkout-finish-extends')
                        <div class="button-contain">
                            <a href="{{ route('home') }}" class="btn">{{ __('Continue shopping') }}</a>
                        </div>
                    </div>
                @endif
            </div>
        </section>
        @if (isset($isValidShowTip) && $isValidShowTip != '' && count($tips) > 0 && isset($tips[$isValidShowTip]) && count($tips[$isValidShowTip]) > 0)
        <div class="tip-container">
            <div class="tip-title">✨ {{ __('Sprinkle a little love — leave a tip!') }} 💖</div>
            <div class="tip-buttons">
                @foreach ($tips[$isValidShowTip] as $tip)
                    <a href="{{ $tip['link'] }}" target="_blank" class="tip-button">{{ $tip['amount'] }} <span>{{ __($tip['description']) }}</span></a>
                @endforeach
            </div>
        </div>
        @endif
        @include('cart::includes.e-card-gift')
    </div>
    @include('cart::includes.explore-products')
@endsection

@section('conversion-js')
     <script>
        window.dataLayer.push({  'shippingDeduction': <?= isset($shippingDeduction) ? $shippingDeduction : 0 ?> });
        window.dataLayer.push({  'discount': <?= isset($discount) ? $discount : 0 ?> });
        window.dataLayer.push({  'discountAfterChange': <?= isset($discountAfterChange) ? $discountAfterChange : 0 ?> });
        window.dataLayer.push({  'languageCode': "<?= strtoupper(env('LANGUAGE_CODE','en')) ?>" });
        window.dataLayer.push({  'countryCode': "<?= strtoupper(env('LOCALE_SHIPPING','US')) ?>" });
        window.dataLayer.push({  'feedLabel': "<?= strtoupper(env('LOCALE_SHIPPING','US')) ?>" });
        window.dataLayer.push({  'merchantId': "<?= getOption('merchant_id', '398409240') ?>" });
        window.dataLayer.push({  'transactionTotal': <?= isset($profit) ? $profit : 0 ?> });
        window.dataLayer.push({  'profitvalue': <?= isset($profit) ? $profit : 0 ?> });
        window.dataLayer.push({  'profitAfterChange': <?= isset($profitAfterChange) ? $profitAfterChange : 0 ?> });
        window.dataLayer.push({  'currencyConvert': "<?= isset($currencyConvert) ? $currencyConvert : env('CURRENCY_UNIT','USD') ?>" });
        window.dataLayer.push({  'cjAmount': <?= isset($cjAmount) ? $cjAmount : '' ?> });
        window.dataLayer.push({'transactionId': '<?= isset($order["code"]) ? $order["code"]:0 ?>'});
        window.dataLayer.push({'transactionDiscount': '<?= isset($order["discount"]) ? $order["discount"]:0 ?>'});
        window.dataLayer.push({'transactionCoupon': '<?= isset($order["promotion_code"]) ? $order["promotion_code"]:"" ?>'});
        window.dataLayer.push({'currency': "<?= env('CURRENCY_UNIT','USD') ?>"});
        window.dataLayer.push({'email': "<?= isset($customerOrder['email']) ? $customerOrder['email'] : '' ?>"});
        window.dataLayer.push({'customerId': "<?= isset($order['customer_id']) ? $order['customer_id'] : '' ?>"});
        window.dataLayer.push({'emailHash': "<?= isset($customerOrder['email']) ? hash('sha256',$customerOrder['email']) : '' ?>"});
        window.dataLayer.push({'event': 'thank_you_page'});
        window.dataLayer.push({'paymentType': "<?= isset($order['payment_type']) ? $order['payment_type'] : '' ?>"});
        window.dataLayer.push({'ignoreType': "<?= isset($ignoreType) ? $ignoreType : '' ?>"});
        window.dataLayer.push({'event': "<?= isset($purchaseEventPixel) ? $purchaseEventPixel : 'none' ?>"});
        window.dataLayer.push({'event': "<?= isset($purchaseEventSeller) ? $purchaseEventSeller : 'none' ?>"});
        window.dataLayer.push({'fromSource': "<?= isset($fromSource) ? $fromSource : 'none' ?>"});
        window.dataLayer.push({'orderAmount': "<?= isset($order['amount']) ? $order['amount'] : 0 ?>"});
        window.uetq = window.uetq || [];
        window.uetq.push('event', '', {'revenue_value': <?= isset($profit) ? $profit : '' ?>, 'currency': "<?= env('CURRENCY_UNIT','USD') ?>"});
        let items = <?= json_encode($order['items']) ?>;
        let homeUrl = '<?= route('home') ?>';
        let ecommerceItems = [];
        let transactionProducts = [];
        let criteoItems = [];
        let criteoLocale = '<?= $criteoLocale ?>'
        let cjItems = [];
        let pinterestProducts = [];
        let twitterProducts = [];
        let facebookProducts = [];
        let contentIds = [];
        let conversionItems = [];
        let drItems = [];
        let trustPilotItems = [];
        let totalProfit = <?= isset($profit) ? $profit : 0 ?>;
        let totalQuantity = <?= isset($totalQuantity) ? $totalQuantity : 0 ?>;
        let avgProfit = 0;
        if(totalQuantity >0 && totalProfit > 0){
            avgProfit = totalProfit/totalQuantity;
        }
        for (let key in items) {
            let item = items[key];
            ecommerceItems.push({item_id:item.sku,item_name:item.name});
            transactionProducts.push({sku:item.sku,name:item.name,price:item.price,quantity:item.quantity});
            criteoItems.push({id:criteoLocale + item.product_id,price:avgProfit,quantity:item.quantity});
            cjItems.push({itemId:item.product_sku,unitPrice:item.price,quantity:item.quantity});
            pinterestProducts.push({product_id:item.sku,category_name:''});
            twitterProducts.push({content_id:item.product_sku,content_price:item.price,num_items:item.quantity,content_name:item.name});
            facebookProducts.push({id:item.product_sku,quantity:item.quantity});
            conversionItems.push({id:item.product_sku,price:item.price,quantity:item.quantity});
            contentIds.push(item.product_sku);
            drItems.push({id:item.product_sku,google_business_vertical: 'retail'});
            trustPilotItems.push({sku:item.product_sku,productUrl: homeUrl+item.url,imageUrl:item.image_url,name:item.name});
        }
        window.dataLayer.push({  'transactionProducts': transactionProducts });
        window.dataLayer.push({  'criteo_items': criteoItems });
        window.dataLayer.push({  'cjItems': cjItems });
        window.dataLayer.push({  'pinterestProducts': pinterestProducts });
        window.dataLayer.push({  'twitterProducts': twitterProducts });
        window.dataLayer.push({  'facebookProducts': facebookProducts });
        window.dataLayer.push({  'content_ids': contentIds });
        window.dataLayer.push({  'conversion_items': conversionItems });
        window.dataLayer.push({
            event: "purchase",
            ecommerce: {
                transaction_id: '<?= isset($order["code"]) ? $order["code"]:0 ?>',
                value: "<?= isset($profit) ? $profit : '' ?>",
                tax: "<?= $order['tax'] ?>",
                shipping: "<?= $order['shipping_fee'] ?>",
                currency: "<?= env('CURRENCY_UNIT','USD') ?>",
                items: ecommerceItems
            }
        });
        window.dataLayer.push({
            'dr_event_type': 'purchase',
            'dr_items':drItems,
            'event':'dynamic_remarketing'
        });
     </script>
     <script src="https://apis.google.com/js/platform.js?onload=renderOptIn" async defer></script>

     <script>
         let currency = '<?= env('CURRENCY_UNIT','USD') ?>';
         let profitValue = '<?= isset($profit) ? $profit : 0 ?>';
         let orderId = '<?= isset($order["code"])?$order["code"]:0 ?>';
         let orderEmail = '<?= isset($order["customer"]["email"])?$order["customer"]["email"]:"" ?>';
         let orderEmailHash = '<?= isset($order["customer"]["email"]) ? hash("sha256",$order["customer"]["email"]) : "" ?>';
         let customerName = '<?= isset($order["customer"]["full_name"])?$order["customer"]["full_name"]:"" ?>';
         let deliveryCountry = '<?= isset($order["country"]["iso"])?$order["country"]["iso"]:"US"?>';
         let deliveryDate = '<?= date("Y-m-d", time() + 86400 * intval($maxTimeShipping)) ?>';
         let isSendFeedBack = '<?= isset($isSendFeedBack) ? $isSendFeedBack : 1 ?>';
         localStorage.removeItem("clickOrder");
     </script>
    @if(function_exists('getOptionByDomain'))
        {!! getOptionByDomain('conversion', '') !!}
    @else 
        {!! getOption('conversion', '') !!}
    @endif
@endsection

@section('js')
@parent
<script type="text/javascript">
    window._uxa = window._uxa || [];
    window._uxa.push(["setCustomVariable", 1, "pageType", "Finish"]);
</script>
<script>
    let urlSite = "<?= route('home') ?>";
    var currencyInsider = "{{ isset($_COOKIE['currency']) ? $_COOKIE['currency'] : config('default.currency_unit') }}";
    let dataDefault = {
        currency: currencyInsider,
        locale: localeInsider,
        type: 'default'
    };

    pushEventInsider(dataDefault);

    let dataPurchase = {
        type: 'purchase',
        value: {
            order_id: "<?= isset($order["code"]) ? $order["code"] : 0 ?>",
            total: <?= isset($order["amount"]) ? $order["amount"] : 0 ?>,
            items: []
        }
    };
    items.forEach(function(item) {
        let size = '';
        let color = '';
        let name = item.name;
        let sizeMatch = name.match(/Size: (\w+)/);
        let colorMatch = name.match(/Color: (\w+)/);
        if (sizeMatch) {
            size = sizeMatch[1];
        }
        if (colorMatch) {
            color = colorMatch[1];
        }
        dataPurchase.value.items.push({
            id: 'sku-' + item.product_sku_id,
            name: item.product_name,
            groupcode: localeInsider + '-' + item.product_id,
            unit_price: parseFloat(item.price),
            unit_sale_price: parseFloat(item.price),
            quantity: parseInt(item.quantity),
            url: homeUrl ? homeUrl + item.url : item.url,
            color: color ?? "",
            size: size ?? "",
            product_image_url: item.image_url,
            custom: {
                merchandiser: "",
                country: localeInsider
            }
        });
    });
    pushEventInsider(dataPurchase);

    function pushEventInsider(data) {
        const newEvent = new CustomEvent('eventInsider', {
            detail: data,
            bubbles: true,
            cancelable: true
        });
        document.dispatchEvent(newEvent);
    }
</script>

<script src="{{ asset('modules/cart/js/e-card-gift.js') }}?v={{ config('sa.version') }}"></script> 
@endsection
<?php
    if (isset($order) && isset($order['id'])) {
        \Log::info("Viewing finished end - locale: " . $localeFinish . " order: " . $order['id']);
    }
?>
