@extends('layouts.app')

@section('content')

<div class="page-wrapper">
    <div class="row page-titles">

        <div class="col-md-5 align-self-center">
            <h3 class="text-themecolor">{{trans('lang.print_order')}}</h3>
        </div>
        <div class="col-md-7 align-self-center">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="{{url('/dashboard')}}">{{trans('lang.dashboard')}}</a></li>

                <?php if(isset($_GET['eid']) && $_GET['eid'] != ''){?>
                <li class="breadcrumb-item"><a
                        href="{{route('restaurants.orders',$_GET['eid'])}}">{{trans('lang.order_plural')}}</a></li>
                <?php }else{ ?>
                <li class="breadcrumb-item"><a href="{!! route('orders') !!}">{{trans('lang.order_plural')}}</a></li>
                <?php } ?>

                <li class="breadcrumb-item">{{trans('lang.print_order')}}</li>
            </ol>
        </div>
    </div>
    <div class="container-fluid">
        <div class="card" id="printableArea" style="font-family: emoji;">
            <div class="col-md-12">
                <div class="print-top non-printable mt-3">
                    <div id="data-table_processing" class="dataTables_processing panel panel-default non-printable"
                        style="display: none;">{{trans('lang.processing')}}</div>
                    <div class="text-right print-btn non-printable"><button type="button"
                            class="fa fa-print non-printable" onclick="printDiv('printableArea')"></button></div>
                </div>

                <hr class="non-printable">
            </div>
            <div class="col-12">
                <div class="text-center pt-4 mb-3">
                    <h2 style="line-height: 1"><label class="storeName"></label></h2>
                    <h5 style="font-size: 20px;font-weight: lighter;line-height: 1">
                        <label class="storeAddress"></label>
                    </h5>
                    <h5 style="font-size: 16px;font-weight: lighter;line-height: 1">
                        {{trans('lang.phone')}} :
                        <label class="storePhone"></label>
                    </h5>
                </div>
                <span>-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------</span>
                <div class="row mt-3">
                    <div class="col-6">
                        <h5>{{trans('lang.order_id')}} : <label class="orderId"></label></h5>
                    </div>
                    <div class="col-6">
                        <h5 style="font-weight: lighter">
                            <label class="orderDate"></label>

                        </h5>
                    </div>
                    <div class="col-12">
                        <h5>
                            {{trans('lang.customer_name')}} :
                            <label class="customerName"></label>
                        </h5>
                        <h5>
                            {{trans('lang.phone')}} :

                            <label class="customerPhone"></label>
                        </h5>
                        <h5 class="text-break">
                            {{trans('lang.address')}} :

                            <label class="customerAddress"></label>
                        </h5>
                    </div>
                </div>
                <h5 class="text-uppercase"></h5>
                <span>-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------</span>
                <table class="table table-bordered mt-3" style="width: 92%">
                    <thead>
                        <tr>
                            <th>{{trans('lang.item')}}</th>
                            <th>{{trans('lang.price')}}</th>
                            <th>{{trans('lang.qty')}}</th>
                            <th>{{trans('lang.extras')}}</th>
                            <th>{{trans('lang.total')}}</th>
                        </tr>
                    </thead>
                    <tbody id="order_products">

                    </tbody>
                </table>
                <span>-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------</span>
                <div class="row justify-content-md-end mb-3" style="width: 97%">
                    <div class="col-md-7 col-lg-7">
                        <dl class="row text-right">
                            <dt class="col-6">{{trans('lang.items_price')}} :</dt>
                            <dd class="col-6"><label class="total_item_price"></label>
                            </dd>
                            <dt class="col-6">{{trans('lang.addon_cost')}} :</dt>
                            <dd class="col-6">
                                <label class="total_addon_price"></label>
                                <hr>
                            </dd>
                            <dt class="col-6">{{trans('lang.sub_total')}} :</dt>
                            <dd class="col-6">
                                <label class="total_price"></label>
                            </dd>
                            <dt class="col-6">{{trans('lang.discount')}} :</dt>
                            <dd class="col-6">
                                -
                                <label class="total_discount_amount"></label>
                            </dd>

                            <span class="taxes row w-100 m-0"></span>
                            <dt class="col-6">{{trans('lang.dm_tips')}} :</dt>
                            <dd class="col-6">
                                <label class="total_tip_amount">+ $ 0</label>
                            </dd>
                            <dt class="col-6">{{trans('lang.deliveryFee')}} :</dt>
                            <dd class="col-6">
                                <label class="total_delivery_amount">+ $ 0</label>
                                <hr>
                            </dd>
                            <dt class="col-6" style="font-size: 20px">{{trans('lang.total')}} :
                            </dt>
                            <dd class="col-6" style="font-size: 20px">
                                <label class="total_amount"></label>
                            </dd>
                        </dl>
                    </div>
                </div>
                <span>-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------</span>
                <h5 class="text-center pt-3">
                    {{trans('lang.thank_you')}}
                </h5>
                <span>-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------</span>
            </div>
        </div>
    </div>

    @endsection

    @section('style')
    <style type="text/css">
    #printableArea * {
        color: black !important;
    }

    @media print {
        @page { size: portrait; }

        .non-printable { display: none; }
        .printable { display: block; font-family: emoji !important; }
        #printableArea { width: 400px; }

        body {
            -webkit-print-color-adjust: exact !important;
            color-adjust: exact !important;
            font-family: emoji !important;
        }
    }
    </style>
    <style type="text/css" media="print">
    @page { size: portrait; }
    @page { size: auto; margin: 2px; font-family: emoji !important; }
    </style>
    @endsection

    @section('scripts')
    <script>
    var id = "<?php echo $id; ?>";

    document.addEventListener('DOMContentLoaded', function () {
        jQuery('#data-table_processing').show();

        fetch('/api/orders/' + encodeURIComponent(id) + '/print', {
            headers: { 'Accept': 'application/json' }
        })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            var order    = data.order;
            var vendor   = data.vendor;
            var currency = data.currency;

            var sym   = currency.symbol        || '€';
            var right = currency.symbolAtRight || false;
            var dec   = currency.decimalDigits  || 2;

            function fmt(val) {
                var n = parseFloat(val || 0).toFixed(dec);
                return right ? (n + sym) : (sym + n);
            }

            // Store info
            $('.storeName').text(vendor.title   || '');
            $('.storePhone').text(vendor.phone  || '');
            $('.storeAddress').text(vendor.address || '');
            if (vendor.photo) { $('.resturant-img').attr('src', vendor.photo); }

            // Order header
            $('.orderId').text(order.id);
            $('.customerName').text(order.customerName    || '');
            $('.customerPhone').text(order.customerPhone  || '');
            $('.customerAddress').text(order.customerAddress || '');

            if (order.createdAt) {
                var d   = new Date(order.createdAt);
                var pad = function(n) { return String(n).padStart(2, '0'); };
                var dateStr = d.getFullYear() + '-' + pad(d.getMonth()+1) + '-' + pad(d.getDate());
                var timeStr = d.toLocaleTimeString('en-US');
                $('.orderDate').text(dateStr + ' ' + timeStr);
                $('#createdAt').text(dateStr + ' ' + timeStr);
            }

            if (order.paymentMethod) {
                var pmLabel = order.paymentMethod === 'cod'
                    ? '{{trans("lang.cash_on_delivery")}}'
                    : order.paymentMethod;
                $('#payment_method').text(pmLabel);
            }

            if (order.takeAway) {
                $('#order_type').text('{{trans("lang.order_takeaway")}}');
                $('.payment_method').hide();
            } else {
                $('#order_type').text('{{trans("lang.order_delivery")}}');
            }

            // Products table
            var html       = '';
            var totalItems = 0;

            (order.products || []).forEach(function(p) {
                var itemTotal  = parseFloat(p.price || 0) * parseInt(p.quantity || 1);
                var extrasHtml = '';
                if (p.extras && p.extras.length) {
                    extrasHtml = '<div class="extra"><span>{{trans("lang.extras")}} :</span>'
                        + '<span class="ext-item">' + p.extras.join(', ') + '</span></div>';
                }
                totalItems += parseFloat(p.price || 0);

                html += '<tr>';
                html += '<td class="order-product"><div class="orders-tracking"><h6>'
                    + (p.name || '') + '</h6>' + extrasHtml + '</div></td>';
                html += '<td>' + fmt(p.price) + '</td>';
                html += '<td>' + (p.quantity || 1) + '</td>';
                html += '<td>+ ' + fmt(0) + '</td>';
                html += '<td>' + fmt(itemTotal) + '</td>';
                html += '</tr>';
            });

            document.getElementById('order_products').innerHTML = html;
            $('.total_item_price').text(fmt(totalItems));
            $('.total_addon_price').text(fmt(0));
            $('.total_price').text(fmt(order.subtotal      || 0));
            $('.total_discount_amount').text(fmt(order.discountAmount || 0));
            $('.total_tip_amount').text('+ ' + fmt(order.tipAmount    || 0));
            $('.total_delivery_amount').text('+ ' + fmt(order.deliveryCharge || 0));
            $('.total_amount').text(fmt(order.totalAmount  || 0));

            jQuery('#data-table_processing').hide();
        })
        .catch(function(err) {
            console.error('Failed to load order for print:', err);
            jQuery('#data-table_processing').hide();
        });
    });

    function printDiv(divName) {
        var printContents = document.getElementById(divName).innerHTML;
        var originalContents = document.body.innerHTML;
        document.body.innerHTML = printContents;
        window.print();
        document.body.innerHTML = originalContents;
    }
    </script>
    @endsection