<?php
    class Menu {
        public function __construct(Database $db) {
            $this->db = $db;
        }
        public function get($data = array(), $parent = 0) {
            $menu = array();
            $sub_items = array();
            $query = "SELECT id, title, link, parent, icon, col, class, target FROM {$this->db->prefix}menu WHERE status=1 AND parent=" . (int)$parent;
            
            if(isset($data['position'])){
                $query .= " AND position = '{$data['position']}'";
            }

            if(isset($data['col'])){
                $query .= " AND col =".$data['col'];
            }

            if(isset($data['sort'])){
                $query .= " ORDER BY " . $data['sort'];
            }else{
                $query .= " ORDER BY `sort_order`";
            }
    
            if(isset($data['order'])){
                $query .= " ".$data['order'];
            }else{
                $query .= " ASC";
            }

            $result = $this->db->query($query);
            foreach($result->rows as $row){
                $sub_items = $this->isHaveChildren($row["id"]) ? $this->get($data, $row["id"]) : array();
                $item = array(
                    'id'                     => $row["id"],
                    'title'                  => $row["title"],
                    'link'                   => $row["link"],
                    'icon'                   => $row["icon"],
                    'col'                    => $row["col"],
                    'class'                  => $row["class"],
                    'target'                 => $row["target"],
                    'sub_items'              => empty($sub_items) ? "" : $sub_items
                );
                array_push($menu, $item);
            }

            return $menu;
        }

        public function isHaveChildren($id) {
            $result = $this->db->query("SELECT COUNT(id) AS 'count' FROM {$this->db->prefix}menu WHERE status=1 AND parent=:parent", array(':parent'=>$id));
            if($result->row['count']>0){
                return true;
            }
            return false;
        }

        public function getActiveMenuItemId($request_id) {
            $result = $this->db->query("SELECT id, parent FROM {$this->db->prefix}menu WHERE status=1 AND link=:link", array(':link'=>$request_id));
            if($result->num_rows>0){
                return array('id'=>$result->row['id'], 'parent'=>$result->row['parent']);
            }
            return array('id'=>0, 'parent'=>0);
        }

        public function getMenuItems($data = array()) {
            $items = array();
            $query = "SELECT * FROM {$this->db->prefix}menu WHERE 1";
            
            if(isset($data['status'])){
                if($data['status'] != ''){
                    $query .= " AND status =".$data['status'];
                }
            }
            
            if(isset($data['position'])){
                if($data['position'] != ''){
                    $query .= " AND position ='".$data['position']."'";
                }
            }

            if(isset($data['search_keywords'])){
                $keywords = explode(' ', $data['search_keywords']);
                $searchTermKeywords = array();
                foreach ($keywords as $word) {
                    $word                 = $this->db->escape($word);
                    $searchTermKeywords[] = "(title LIKE '%$word%' OR link LIKE '%$word%')";
                }
                $query .= ' AND '.implode(' AND ', $searchTermKeywords);
            }
            
            if(isset($data['sort'])){
                $query .= " ORDER BY `" . $data['sort']."`";
            }else{
                $query .= " ORDER BY id";
            }
    
            if(isset($data['order'])){
                $query .= " ".$data['order'];
            }else{
                $query .= " DESC";
            }
    
            if (isset($data['offset']) || isset($data['limit'])) {
                if($data['offset'] < 0){
                    $data['offset'] = 0;
                }
    
                if($data['limit'] < 1){
                    $data['limit'] = 24;
                }
    
                $query .= " LIMIT " . (int)$data['offset'] . "," . (int)$data['limit'];
            }
            
            $stmt = $this->db->query($query);
            if($stmt->num_rows > 0) {
                foreach($stmt->rows as $row){ 
                    $status = $row['status'];
                    if($status == 1) {
                        $status = '<span class="badge bg-success">Aktif</span>';
                    }else if($status == 0) {
                        $status = '<span class="badge bg-danger">Pasif</span>';
                    }else {
                        $status = 'Bilinmiyor';
                    }
                    $position = $row['position'];
                    if($position == 'main') {
                        $position = 'Ana Menü';
                    }else if($position == 'footer') {
                        $position = 'Site Alt Kısım';
                    }else if($position == 'top-bar') {
                        $position = 'Site Üst Kısım';
                    }else if($position == 'account-sidebar-menu') {
                        $position = 'Kullanıcı Menüsü';
                    }else if($position == 'sidebar') {
                        $position = 'Kullanıcı Paneli';
                    }

                    $parent = $this->getParent($row['parent']);
                    $item = array(
                        'id'                     => $row['id'],
                        'status'                 => $status,
                        'title'                  => $row['title'],
                        'link'                   => $row['link'],
                        'sort_order'             => $row['sort_order'],
                        'position'               => $row['position'],
                        'position_text'          => $position,
                        'icon'                   => $row['icon'],
                        'col'                    => $row['col'],
                        'class'                  => $row['class'],
                        'parent'                 => $row['parent'],
                        'parent_text'            => $parent['title']
                    );
                    array_push($items, $item);
                }
            }

            return $items;
        }

        public function getTotalMenuItems($data = array()){
            $query = "SELECT COUNT(id) AS 'total' FROM {$this->db->prefix}menu WHERE 1";
            
            if(isset($data['status'])){
                if($data['status'] != ''){
                    $query .= " AND status =".$data['status'];
                }
            }
            if(isset($data['position'])){
                if($data['position'] != ''){
                    $query .= " AND position ='".$data['position']."'";
                }
            }

            if(isset($data['search_keywords'])){
                $keywords = explode(' ', $data['search_keywords']);
                $searchTermKeywords = array();
                foreach ($keywords as $word) {
                    $word                 = $this->db->escape($word);
                    $searchTermKeywords[] = "(title LIKE '%$word%' OR link LIKE '%$word%')";
                }
                $query .= ' AND '.implode(' AND ', $searchTermKeywords);
            }
            
            $stmt = $this->db->query($query);
            if($stmt->num_rows > 0){
                return $stmt->row['total'];
            }

            return 0;
        }

        public function getMenuItem($id) {
            $query = "SELECT * FROM {$this->db->prefix}menu WHERE id=:id";
            $stmt = $this->db->query($query, array(':id'=>$id));
            if($stmt->num_rows > 0) {
                return $stmt->row;
            }

            return array();
        }

        public function deleteMenuItem($id) {
            $this->db->query("DELETE FROM {$this->db->prefix}menu WHERE id=:id", array(':id'=>$id));
        }

        public function getParent($id) {
            $result = $this->db->query("SELECT id, title FROM {$this->db->prefix}menu WHERE id=:id", array(':id'=>$id));
            if($result->num_rows>0){
                return array('id'=>$result->row['id'], 'title'=>$result->row['title']);
            }
            return array('id'=>0, 'title'=>'');
        }




        public function getBanners($data = array()) {
            $banners = array();
            $query = "SELECT * FROM {$this->db->prefix}menu_banners WHERE 1";
            
            if(isset($data['status'])){
                if($data['status'] != ''){
                    $query .= " AND status =".$data['status'];
                }
            }

            if(isset($data['search_keywords']) && !empty($data['search_keywords'])){
                $keywords = explode(' ', $data['search_keywords']);
                $searchTermKeywords = array();
                foreach ($keywords as $word) {
                    $word                 = $this->db->escape($word);
                    $searchTermKeywords[] = "(title LIKE '%$word%' OR link LIKE '%$word%')";
                }
                $query .= ' AND '.implode(' AND ', $searchTermKeywords);
            }
            
            if(isset($data['sort'])){
                $query .= " ORDER BY `" . $data['sort']."`";
            }else{
                $query .= " ORDER BY id";
            }
    
            if(isset($data['order'])){
                $query .= " ".$data['order'];
            }else{
                $query .= " DESC";
            }
    
            if (isset($data['offset']) || isset($data['limit'])) {
                if($data['offset'] < 0){
                    $data['offset'] = 0;
                }
    
                if($data['limit'] < 1){
                    $data['limit'] = 24;
                }
    
                $query .= " LIMIT " . (int)$data['offset'] . "," . (int)$data['limit'];
            }
            
            $stmt = $this->db->query($query);
            if($stmt->num_rows > 0) {
                foreach($stmt->rows as $row){ 
                    $status = $row['status'];
                    if($status == 1) {
                        $status = '<span class="badge bg-success">Aktif</span>';
                    }else if($status == 0) {
                        $status = '<span class="badge bg-danger">Pasif</span>';
                    }else {
                        $status = 'Bilinmiyor';
                    }
                    $item = array(
                        'id'                     => $row['id'],
                        'status'                 => $status,
                        'image'                  => $row['image'],
                        'title'                  => $row['title'],
                        'link'                   => $row['link'],
                        'parent'                 => $row['parent']
                    );
                    array_push($banners, $item);
                }
            }

            return $banners;
        }

        public function getTotalBanners($data = array()){
            $query = "SELECT COUNT(id) AS 'total' FROM {$this->db->prefix}menu_banners WHERE 1";
            
            if(isset($data['status'])){
                if($data['status'] != ''){
                    $query .= " AND status =".$data['status'];
                }
            }

            if(isset($data['search_keywords']) && !empty($data['search_keywords'])){
                $keywords = explode(' ', $data['search_keywords']);
                $searchTermKeywords = array();
                foreach ($keywords as $word) {
                    $word                 = $this->db->escape($word);
                    $searchTermKeywords[] = "(title LIKE '%$word%' OR link LIKE '%$word%')";
                }
                $query .= ' AND '.implode(' AND ', $searchTermKeywords);
            }
            
            $stmt = $this->db->query($query);
            if($stmt->num_rows > 0){
                return $stmt->row['total'];
            }

            return 0;
        }

        public function getBanner($id) {
            $query = "SELECT * FROM {$this->db->prefix}menu_banners WHERE id=:id";
            $stmt = $this->db->query($query, array(':id'=>$id));
            if($stmt->num_rows > 0) {
                return $stmt->row;
            }

            return array();
        }

        public function deleteBanner($id) {
            $this->db->query("DELETE FROM {$this->db->prefix}menu_banners WHERE id=:id", array(':id'=>$id));
        }
    }