<?php 
    $data = array();
    $data['title'] = "Bekleyen 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', $config->get('site_url').'admin/public/assets/js/pages/orders/index.js', '/admin/public/assets/js/pages/report.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/list",
        'index' => 2
    );
    $data['breadcrumbs'][] = array(
        'text' => "Bekleyen Siparişler",
        'href' => "/admin/orders/new",
        'index' => 3
    );

    /* Status update */
    if(isset($_POST['update'])){ 
        $order_status        = $_POST['order_status'];
        $selected_orders     = $_POST['selected_orders'];
        
        if(!empty($selected_orders)){
            if($order_status != 0){
                foreach ($selected_orders as $val){
                    $stmt = $db->query("UPDATE {$db->prefix}orders SET status=:status WHERE id=:id", array(':status'=>$order_status, ':id'=>$val));
                    if($stmt->error) {
                        $utils->errorLog("error", "Cannot update order status. Error: ".$stmt->error_info['message'], $session->data['user_id'], $_SERVER['REQUEST_URI']);
                        $session->data['messageType'] = "error"; 
                        $session->data['messageTitle'] = "Hata!"; 
                        $session->data['message'] = "Bir hata oluştu ve siparişler güncellenemedi."; 
                        header("Refresh: 0;");
                        exit();
                    }
                }
                $session->data['messageType'] = "success"; 
                $session->data['messageTitle'] = "Başarılı!"; 
                $session->data['message'] = "Siparişler başarıyla güncellendi."; 
                header("Refresh: 0;");
                exit();
            }
        }
    }
    /* Status update */


    $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') : "";
    $status             = isset($_GET["status"]) ? $_GET["status"] : "";
    $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,
        'status'             => "1,2,3,4,5",
        'date_start'         => $date_start,
        'date_end'           => $date_end,
        'sort'               => $sort,
        'order'              => $sort_order,
        'offset'             => $offset,
        'limit'              => $limit
    );
    
    $orders             = $order->getOrders($filter_data);
    $total_orders 	    = $order->getTotalOrders($filter_data);

    $order_status 	    = $order->getOrderStatusList();
    
    $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 class="col-md-2 text-center text-md-start">
                                    <label for="" class="col-form-label">&nbsp;</label>
                                    <button type="button" class="btn btn-success w-100" data-action="/admin/orders/excel" data-report="sales" data-id="" data-export><i class="bi bi-file-earmark-excel"></i> Excel</button>
                                </div>
                            </div>
                        </form>
                    </div>
                    <form id="orders-filter" method="POST">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover table-bordered table-sortable mb-0">
                                <thead>
                                    <tr>
                                        <th class="check-column"><label class="screen-reader-text" for="cf-select-all"></label><input id="cf-select-all" type="checkbox"></th>
                                        <th style="width:120px;" class="sorting" data-column="order_id" data-order="">Sipariş No</th>
                                        <th class="sorting" data-column="status" data-order="">Durum</th>
                                        <th class="sorting" data-column="name" data-order="">Alıcı Adı</th>
                                        <th class="sorting" data-column="email" data-order="">Sanal Pos</th>
                                        <th class="sorting" data-column="phone" data-order="">Telefon</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>Hediye Notu</th>
                                        <th>Sipariş Notu</th>
                                        <th style="width:150px;"></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                        if($total_orders>0) {
                                            foreach($orders as $row) {
                                                $gift_note = !empty($row['gift_note']) ? "<span class=\"badge text-bg-success\">Var</span>" : "<span class=\"badge text-bg-danger\">Yok</span>";
                                                $order_note = !empty($row['order_note']) ? "<span class=\"badge text-bg-success\">Var</span>" : "<span class=\"badge text-bg-danger\">Yok</span>";
                                                $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>
                                                            <th scope=\"row\" class=\"check-column\"><label class=\"screen-reader-text\" for=\"cf-select-".$row['id']."\"></label> <input id=\"cf-select-".$row['id']."\" type=\"checkbox\" name=\"selected_orders[]\" value=\"".$row['id']."\"></td>
                                                            <td class=\"text-center\">".$row['order_id']."</td>
                                                            <td><span class=\"badge order-status-".$row['status']."\">".$row['status_text']."</span></td>
                                                            <td>".$user_name."</td>
                                                            <td>".$row['payment_gateway']."</td>
                                                            <td>".$phone."</td>
                                                            <td>".$row['date_added']."</td>
                                                            <td>".$utils->moneyFormatter($row['order_total'])." TL</td>
                                                            <td class=\"text-center\">".$gift_note."</td>
                                                            <td class=\"text-center\">".$order_note."</td>
                                                            <td style=\"min-width: 140px;vertical-align: middle;\" class=\"text-center\">
                                                                <a class=\"btn btn-sm btn-primary me-1\" href=\"/admin/orders/edit?id=".$row['id']."&redirect=". urlencode($_SERVER['REQUEST_URI']) ."\"><i class=\"bi bi-pencil-square\"></i></a>
                                                                <a class=\"btn btn-sm btn-secondary me-1\" href=\"/admin/orders/shipping-label?id=" . $row["id"] . "\" target=\"_blank\" title=\"Yazdır\"><i class=\"bi bi-truck\"></i></a>
                                                                <a class=\"btn btn-sm btn-secondary\" href=\"/admin/orders/receipt?id=" . $row["id"] . "\" target=\"_blank\" title=\"Yazdır\"><i class=\"bi bi-receipt\"></i></a>
                                                            </td>
                                                        </tr>";
                                            }
                                        }else{
                                            echo "<tr class=\"text-center\"><td colspan=\"15\">Hiçbir kayıt bulunamadı!</td></tr>";
                                        }
                                    ?>
                                </tbody>
                            </table>
                        </div>
                        <div class="row my-2">
                            <div class="col-md-2 col-5" >
                                <select class="form-control form-control-sm" id="order_status" name="order_status">
                                    <option value="0">Durum Güncelle..</option>
                                    <?php foreach ($order_status as $u): ?>
                                        <option value="<?php echo $u['id']; ?>"><?php echo $u['title']; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6 col-7" >
                                <input type="submit" name="update" id="update" class="btn btn-sm btn-primary me-1 form-control-sm" value="Güncelle">
                                <button type="submit" name="shipping-label" class="btn btn-sm btn-secondary me-1 form-control-sm"><i class="bi bi-truck"></i></button>
                                <button type="submit" name="receipt" class="btn btn-sm btn-secondary me-1 form-control-sm"><i class="bi bi-receipt"></i></button>
                            </div>
                        </div>
                    </form>
                    <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>
<?php include DIR_VIEWS."parts/footer.php"; ?>