<?php 
    $data = array();
    $data['title'] = "Terk Edilen Siparişler | ".$config->get('site_title');
    $data['links'] = [];
    $data['styles'] = ['/admin/public/assets/css/daterangepicker.css'];
    $data['header']['scripts'] = [];
    $data['version'] = $config->get('version');
    $data['csrf_token'] = $csrf_generator->create();
    $data['sidebar_menu'] = $menu->get(array('position'=>'sidebar'));
    $data['sidebar_active_menu'] = $menu->getActiveMenuItemId(trim($_SERVER['REQUEST_URI']));
    $data['footer']['scripts'] = [$config->get('site_url').'admin/public/assets/js/jquery-3.6.0.min.js', $config->get('site_url').'admin/public/assets/js/moment.min.js', $config->get('site_url').'admin/public/assets/js/daterangepicker.js'];
    $menu_items = $menu->get(array('position'=>'footer'));
    foreach($menu_items as $item){
        if($item['col'] == "1"){
            $data['menu']['footer']["1"][] = $item;
        }
        if($item['col'] == "2"){
            $data['menu']['footer']["2"][] = $item;
        }
        if($item['col'] == "3"){
            $data['menu']['footer']["3"][] = $item;
        }
        if($item['col'] == "4"){
            $data['menu']['footer']["4"][] = $item;
        }
    }

    $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
        'text' => "Pano",
        'href' => "/admin",
        'index' => 1
    );
    $data['breadcrumbs'][] = array(
        'text' => "Siparişler",
        'href' => "/admin/orders/abandoned",
        'index' => 2
    );
    $data['breadcrumbs'][] = array(
        'text' => "Terk Edilen Siparişler",
        'href' => "/admin/orders/abandoned",
        'index' => 3
    );



    $search_keywords    = isset($_GET['q']) ? htmlspecialchars($_GET['q'], ENT_QUOTES, 'UTF-8') : "";
    $date_start         = isset($_GET['date_start']) ? htmlspecialchars($_GET['date_start'], ENT_QUOTES, 'UTF-8') : "";
    $date_end           = isset($_GET['date_end']) ? htmlspecialchars($_GET['date_end'], ENT_QUOTES, 'UTF-8') : "";
    $sort               = isset($_GET["sort"]) ? $_GET["sort"] : "id";
    $sort_order         = isset($_GET["order"]) ? $_GET["order"] : "DESC";

    $page               = !isset($_GET["page"]) || $_GET["page"] < 1 ? 1 : (int)$_GET["page"];
    $limit	            = isset($_GET["limit"]) ? (int)$_GET["limit"] : 25;
    $offset             = ($page-1)*$limit;
    $filter_data = array(
        'search_keywords'    => $search_keywords,
        'date_start'         => $date_start,
        'date_end'           => $date_end,
        'sort'               => $sort,
        'order'              => $sort_order,
        'offset'             => $offset,
        'limit'              => $limit
    );
    
    $orders             = $order->getOrderTrials($filter_data);
    $total_orders 	    = $order->getTotalOrderTrials($filter_data);
    
    $pagination->total  = $total_orders;
    $pagination->page   = $page;
    $pagination->limit  = $limit;
    $pagination->url    = '#';
?>
<?php include DIR_VIEWS."parts/header.php"; ?>
        <main class="content">
            <div class="container-fluid">
                <div class="card">
                    <div class="card-header">
                        <form action="" method="GET" id="filter-form">
                            <div class="row">
                                <div class="col-md-4 text-center text-md-start">
                                    <label for="q" class="col-form-label">Anahtar Kelime</label>
                                    <input type="text" name="q" id="q" class="form-control" value="<?php echo $search_keywords; ?>">
                                </div>
                                <div class="col-md-2 text-center text-md-start">
                                    <label for="date" class="col-form-label">Tarih</label>
                                    <input type="text" id="date" class="form-control" value="<?php echo isset($_GET["date_start"]) && !empty($_GET["date_start"]) ? date('m-d-Y', strtotime($date_start))." - ".date('m-d-Y', strtotime($date_end)) : ""; ?>">
                                    <input type="hidden" name="date_start" id="date_start" value="<?php echo $date_start; ?>">
                                    <input type="hidden" name="date_end" id="date_end" value="<?php echo $date_end; ?>">
                                </div>
                                <div class="col-md-2 text-center text-md-start">
                                    <label for="" class="col-form-label">&nbsp;</label>
                                    <button type="submit" class="btn btn-primary w-100">Filtrele</button>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover table-bordered table-sortable mb-0">
                            <thead>
                                <tr>
                                    <th class="sorting" data-column="id" data-order="id">ID</th>
                                    <th class="sorting" data-column="name" data-order="">Alıcı Adı</th>
                                    <th class="sorting" data-column="address" data-order="">Adres</th>
                                    <th class="sorting" data-column="phone" data-order="">Telefon</th>
                                    <th class="sorting" data-column="payment_gateway" data-order="">Sanal Pos</th>
                                    <th class="sorting" data-column="date_added" data-order="">İşlem Tarihi</th>
                                    <th class="sorting" data-column="order_total" data-order="">Tutar</th>
                                    <th class="sorting" data-column="source" data-order="">Kaynak</th>
                                    <th class="sorting" data-column="email_sent" data-order="">Hatırlatma Maili</th>
                                    <th style="width:50px;"></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                    if($total_orders>0) {
                                        foreach($orders as $row) {
                                            $user_name = $row['user_id'] != 0 ? "<a href=\"/admin/users/edit?user_id=".$row['user_id']."\" target=\"_blank\">".$row['name']." ".$row['surname']."</a>" : $row['name']." ".$row['surname'];
                                            $phone = empty($row['phone']) ? $row['shipping_phone'] : $row['phone'];
                                            echo "<tr>
                                                        <td>".$row['id']."</td>
                                                        <td>".$user_name."</td>
                                                        <td>".$row['shipping_address']." ".$row['shipping_city']."/".$row['shipping_town']."</td>
                                                        <td>".$phone."</td>
                                                        <td>".$row['payment_gateway']."</td>
                                                        <td>".$row['date_added']."</td>
                                                        <td>".$utils->moneyFormatter($row['order_total'])." TL</td>
                                                        <td>".$row['source']."</td>
                                                        <td class=\"text-center\">".$row['email_sent']."</td>
                                                        <td style=\"min-width: 50px;vertical-align: middle;\" class=\"text-center\">
                                                            <button type=\"button\" class=\"btn btn-sm btn-primary\" data-bs-toggle=\"modal\" data-bs-target=\"#order-items-modal\" data-items=\"". htmlspecialchars($row['items'], ENT_QUOTES)."\"><i class=\"bi bi-pencil-square\"></i></button>
                                                        </td>
                                                    </tr>";
                                        }
                                    }else{
                                        echo "<tr class=\"text-center\"><td colspan=\"15\">Hiçbir kayıt bulunamadı!</td></tr>";
                                    }
                                ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="d-flex table-responsive align-items-center justify-content-center mt-3">
                        <div class="table-responsive">
                            <nav aria-label="Page navigation">
                                <ul class="pagination" id="pagination">
                                    <?php echo $pagination->render(); ?>
                                </ul>
                            </nav>
                        </div>
                    </div>
                </div>
            </div>
        </main>
        <div class="modal fade" tabindex="-1" id="order-items-modal">
            <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title fw-bold">Sepet İçeriği</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body p-0">
                        <div class="table-responsive">
                            <table class="table table-condensed table-striped table-bordered">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Ürün Adı</th>
                                        <th>Miktar</th>
                                        <th>Fiyat</th>
                                    </tr>
                                </thead>
                                <tbody>

                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tamam</button>
                    </div>
                </div>
            </div>
        </div>
<?php include DIR_VIEWS."parts/footer.php"; ?>
        <script>
            const orderItemsModal = document.getElementById('order-items-modal')
            orderItemsModal.addEventListener('show.bs.modal', event => {
                const data = event.relatedTarget.getAttribute('data-items');
                const modalBodyTable = orderItemsModal.querySelector('.modal-body table tbody');
                try {
                    items = JSON.parse(data);
                    if (!(items instanceof Array)) {
                        console.log('bad data');
                    } else {
                        var html = "";
                        items.forEach((item)=> {
                            html += "<tr><td>"+item.id+"</td><td><a href=\"/"+item.url+"\" target=\"_blank\">"+item.title+"</a></td><td>"+item.quantity+"</td><td>"+item.total+"</td></tr>";
                        });
                    }
                } catch (e) {
                    //console.log('bad data');
                }
                modalBodyTable.innerHTML = html
            });
            $('#date').daterangepicker({
                locale: { cancelLabel: 'Sil', customRangeLabel: "Özel Seçim" },
                buttonClasses: ' btn',
                applyClass: 'btn-primary',
                cancelClass: 'btn-secondary',
                ranges: {
                    'Bugün': [moment(), moment()],
                    'Dün': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                    'Son 7 Gün': [moment().subtract(6, 'days'), moment()],
                    'Son 30 Gün': [moment().subtract(29, 'days'), moment()],
                    'Bu Ay': [moment().startOf('month'), moment().endOf('month')],
                    'Geçen Ay': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
                }
            }, function (start, end, label) {
                document.getElementById('date_start').value = start.format('YYYY-MM-DD');
                document.getElementById('date_end').value = end.format('YYYY-MM-DD');
            });

            $('#date').on('cancel.daterangepicker', function (ev, picker) {
                document.getElementById('date_start').value = "";
                document.getElementById('date_end').value = "";
            });
        </script>