<?php 
    $data = array();
    $data['title'] = "Ürünler | ".$config->get('site_title');
    $data['links'] = [];
    $data['styles'] = [];
    $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'] = ['/admin/public/assets/js/pages/product/list.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' => "Ürünler",
        'href' => "/admin/product/list",
        'index' => 2
    );

    /* Status update */
    if(isset($_POST['update'])){ 
        $product_status        = $_POST['status'];
        $selected_products     = $_POST['selected_products'];
        
        if(!empty($selected_products)){
            if($product_status != ""){
                foreach ($selected_products as $val){
                    $stmt = $db->query("UPDATE {$db->prefix}products SET status=:status WHERE id=:id", array(':status'=>$product_status, ':id'=>$val));
                    if($stmt->error) {
                        $utils->errorLog("error", "Cannot update product 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'] = "Ürünler başarıyla güncellendi."; 
                header("Refresh: 0;");
                exit();
            }
        }
    }
    /* Status update */

    $search_keywords    = isset($_GET['q']) ? htmlspecialchars($_GET['q'], ENT_QUOTES, 'UTF-8') : "";
    $category_id        = isset($_GET["category"]) ? (int)strip_tags($_GET["category"]) : 0;
    $status             = isset($_GET["status"]) ? $_GET["status"] : "";
    $brand_id           = isset($_GET["brand_id"]) ? (int)strip_tags($_GET["brand_id"]) : 0;
    $sort               = isset($_GET["sort"]) ? $_GET["sort"] : "p.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,
        'brand_id'           => $brand_id,
        'category_id'        => $category_id,
        'status'             => $status,
        'sort'               => $sort,
        'order'              => $sort_order,
        'offset'             => $offset,
        'limit'              => $limit
    );
    
    $filter_bar         = !empty($search_keywords) || $status != "" || $category_id != 0 || $brand_id != 0 ? true : false;
    
    $products           = $product->getProducts($filter_data);
    $total_products 	= $product->getTotalProducts($filter_data);

    $brands 	        = $product->getBrands();
    $categories 	    = $product->getCategories();
    
    $pagination->total  = $total_products;
    $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">
                        <h5 class="card-title">Ürünler</h5>
                        <a href="/admin/product/add" class="btn btn-primary btn-sm me-2"><i class="bi bi-plus-circle-dotted"></i> Yeni</a>
                        <button type="button" class="btn btn-success btn-sm me-2" data-bs-toggle="modal" data-bs-target="#reports-modal"><i class="bi bi-file-earmark-excel"></i> Excel</button>
                        <button type="button" class="btn btn-light btn-sm <?php echo $filter_bar ? '' : 'collapsed'; ?>" data-bs-toggle="collapse" data-bs-target="#filter-bar" aria-expanded="true" aria-controls="filter-bar">
                            <i class="bi bi-funnel"></i> Filtre
                        </button>
                    </div>
                    <div class="collapse show" id="filter-bar">
                        <div class="card p-3 mb-0 border-0">
                            <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="search" 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="status" class="col-form-label">Durum</label>
                                        <select name="status" id="status" class="form-control form-select">
                                            <option value="" <?php echo $status == '' ? 'selected' : ''; ?>>Seçiniz</option>
                                            <option value="1" <?php echo $status == "1" ? 'selected' : ''; ?>>Satışta</option>
                                            <option value="0" <?php echo $status == "0" ? 'selected' : ''; ?>>Satışa Kapalı</option>
                                        </select>
                                    </div>
                                    <div class="col-md-2 text-center text-md-start">
                                        <label for="category" class="col-form-label">Kategori</label>
                                        <select name="category" id="category" class="form-control form-select">
                                            <option value="">Seçiniz</option>
                                            <?php foreach ($categories as $c): ?>
                                                <option value="<?php echo $c['id']; ?>" <?php echo $category_id != '' && $category_id == $c['id'] ? 'selected' : ''; ?> class="fw-bold"><?php echo $c['title']; ?></option>
                                                <?php if (!empty($c['sub_items'])): ?>
                                                    <?php foreach ($c['sub_items'] as $s1): ?>
                                                        <option value="<?php echo $s1['id']; ?>" <?php echo $category_id != '' && $category_id == $s1['id'] ? 'selected' : ''; ?>>&nbsp;&nbsp;<?php echo $c['title']; ?> > <?php echo $s1['title']; ?></option>
                                                        <?php if (!empty($s1['sub_items'])): ?>
                                                            <?php foreach ($s1['sub_items'] as $s2): ?>
                                                                <option value="<?php echo $s2['id']; ?>" <?php echo $category_id != '' && $category_id == $s2['id'] ? 'selected' : ''; ?>>&nbsp;&nbsp;&nbsp;&nbsp;<?php echo $c['title']; ?> > <?php echo $s1['title']; ?> > <?php echo $s2['title']; ?></option>
                                                            <?php endforeach; ?>
                                                        <?php endif; ?>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-2 text-center text-md-start">
                                        <label for="brand_id" class="col-form-label">Marka</label>
                                        <select name="brand_id" id="brand_id" class="form-control form-select">
                                            <option value="">Seçiniz</option>
                                            <?php foreach ($brands as $t): ?>
                                                <option value="<?php echo $t['id']; ?>" <?php echo $brand_id != '' && $brand_id == $t['id'] ? 'selected' : ''; ?>><?php echo $t['title']; ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-2 text-center text-md-start">
                                        <label for="skin" class="col-form-label">&nbsp;</label>
                                        <button type="submit" class="btn btn-primary w-100">Filtrele</button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </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:60px;" class="sorting" data-column="p.id" data-order="">ID</th>
                                        <th style="width:60px;">Resim</th>
                                        <th style="width:100px;" class="sorting" data-column="p.status" data-order="">Durum</th>
                                        <th style="width:100px;" class="sorting" data-column="p.sku" data-order="">Stok Kodu</th>
                                        <th class="sorting" data-column="p.title" data-order="">Ürün Adı</th>
                                        <th>Kategori</th>
                                        <th>Marka</th>
                                        <th class="sorting" data-column="stock_level" data-order="">Stok</th>
                                        <th class="sorting" data-column="selling_price" data-order="">Fiyat</th>
                                        <th style="width:180px;"></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                        if($total_products>0) {
                                            foreach($products as $row) {
                                                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_products[]\" value=\"".$row['id']."\"></td>
                                                            <td class=\"text-center\">".$row['id']."</td>
                                                            <td style=\"width: 60px;\" class=\"text-center\"><a href=\"/public/assets/images/products/medium/".$row['image']."\" class=\"glightbox\"> <img src=\"/public/assets/images/products/thumb/".$row['image']."\"/> </a></td>
                                                            <td style=\"width: 100px;\" class=\"text-center\">".$row['status']."</td>
                                                            <td style=\"width: 100px;\" class=\"text-center\">".$row['sku']."</td>
                                                            <td>".$row['title']."</td>";
                                                            if(!empty($row['categories'])) {
                                                                $categoriesx = array();
                                                                foreach($row['categories'] as $category) {
                                                                    array_push($categoriesx, $category['title']);
                                                                }
                                                                echo "<td style=\"width: 300px; overflow-x: hidden; text-overflow: ellipsis;\">".implode(', ', $categoriesx)."</td>";
                                                            }else{
                                                                echo "<td></td>";
                                                            }
                                                            echo "<td class=\"text-center\">".$row['brand']."</td>
                                                            <td class=\"text-center\">".$row['stock_level']."</td>";
                                                            if($row['discount_rate'] != 0) {
                                                                echo "<td><del>".$utils->moneyFormatter($row['price'])." ₺</del> ".$utils->moneyFormatter($row['selling_price'])." ₺</td>";
                                                            }else{
                                                                echo "<td>".$utils->moneyFormatter($row['selling_price'])." ₺</td>";
                                                            }
                                                        echo "<td style=\"width: 180px;vertical-align: middle;\" class=\"text-center\">
                                                                <a class=\"btn btn-sm btn-primary me-1\" href=\"/admin/product/edit?id=".$row['id']."&redirect=". urlencode($_SERVER['REQUEST_URI']) ."\"><i class=\"bi bi-pencil-square\"></i></a>
                                                                <button class=\"btn btn-sm btn-warning me-1 d-none\" type=\"button\" data-bs-toggle=\"modal\" data-bs-target=\"#reports-modal\" data-id=\"".$row['id']."\"><i class=\"bi bi-graph-up\"></i></button>
                                                                <a class=\"btn btn-sm btn-info me-1 text-white\" href=\"/".$row['url']."\" target=\"_blank\"><i class=\"bi bi-send\"></i></a>
                                                                <button class=\"btn btn-sm btn-danger\" data-delete data-href=\"/admin/product/delete?id=".$row['id']."&redirect=". urlencode($_SERVER['REQUEST_URI']) ."\"><i class=\"bi bi-trash\"></i></button>
                                                            </td>
                                                        </tr>";
                                            }
                                        }else{
                                            echo "<tr class=\"text-center\"><td colspan=\"8\">Hiçbir kayıt bulunamadı!</td></tr>";
                                        }
                                    ?>
                                </tbody>
                            </table>
                        </div>
                        <div class="row my-2">
                            <div class="col-md-2 col-6" >
                                <select class="form-control form-control-sm" id="product_status" name="status">
                                    <option value="">Durum Güncelle..</option>
                                    <option value="1">Satışta</option>
                                    <option value="0">Satışa Kapalı</option>
                                </select>
                            </div>
                            <div class="col-md-2 col-6" >
                                <input type="submit" name="update" id="update" class="btn btn-sm btn-primary form-control-sm" value="Güncelle">
                            </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>
        <div class="modal fade" id="reports-modal" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Ürün Raporları</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <button type="button" class="btn btn-primary w-100" data-action="/admin/product/excel" data-report="sales" data-id="" data-export>Ürün Satış Raporu</button>
                            </div>
                            <div class="col-md-6 mb-3">
                                <button type="button" class="btn btn-primary w-100" data-action="/admin/product/excel" data-report="" data-id="" data-export>Ürün Listesi</button>
                            </div>
                            <div class="col-md-6 mb-3">
                                <button type="button" class="btn btn-primary w-100" data-action="/admin/product/excel" data-report="stock" data-id="" data-export>Stok Raporu</button>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Vazgeç</button>
                    </div>
                </div>
            </div>
        </div>
<?php include DIR_VIEWS."parts/footer.php"; ?>