<?php
    class Utils {
        const SECONDS_IN_A_MINUTE = 60;
        const SECONDS_IN_A_HOUR = 3600;
        const SECONDS_IN_AN_HOUR = 3600;
        const SECONDS_IN_A_DAY = 86400;
        const SECONDS_IN_A_WEEK = 604800;
        const SECONDS_IN_A_MONTH = 2592000;
        const SECONDS_IN_A_YEAR = 31536000;
        const HTTP_URL_REPLACE = 1;
        const HTTP_URL_JOIN_PATH = 2;
        const HTTP_URL_JOIN_QUERY = 4;
        const HTTP_URL_STRIP_USER = 8;
        const HTTP_URL_STRIP_PASS = 16;
        const HTTP_URL_STRIP_AUTH = 32;
        const HTTP_URL_STRIP_PORT = 64;
        const HTTP_URL_STRIP_PATH = 128;
        const HTTP_URL_STRIP_QUERY = 256;
        const HTTP_URL_STRIP_FRAGMENT = 512;
        const HTTP_URL_STRIP_ALL = 1024;

        public function __construct(Database $db){
            $this->db = $db;
        }

        public function getUserIP(){
            // Get real visitor IP behind CloudFlare network
            if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
                $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
                $_SERVER['HTTP_CLIENT_IP'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
            }
            $client  = @$_SERVER['HTTP_CLIENT_IP'];
            $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
            $remote  = $_SERVER['REMOTE_ADDR'];
        
            if(filter_var($client, FILTER_VALIDATE_IP)){
                $ip = $client;
            }else if(filter_var($forward, FILTER_VALIDATE_IP)){
                $ip = $forward;
            }else{
                $ip = $remote;
            }
            return $ip;
        }

        public function getUserOS() { 
            $user_agent = $_SERVER['HTTP_USER_AGENT'];
            $os_platform =   "Bilinmeyen İşletim Sistemi";
            $os_array =   array(
                '/windows nt 10/i'      =>  'Windows 10',
                '/windows nt 6.3/i'     =>  'Windows 8.1',
                '/windows nt 6.2/i'     =>  'Windows 8',
                '/windows nt 6.1/i'     =>  'Windows 7',
                '/windows nt 6.0/i'     =>  'Windows Vista',
                '/windows nt 5.2/i'     =>  'Windows Server 2003/XP x64',
                '/windows nt 5.1/i'     =>  'Windows XP',
                '/windows xp/i'         =>  'Windows XP',
                '/windows nt 5.0/i'     =>  'Windows 2000',
                '/windows me/i'         =>  'Windows ME',
                '/win98/i'              =>  'Windows 98',
                '/win95/i'              =>  'Windows 95',
                '/win16/i'              =>  'Windows 3.11',
                '/macintosh|mac os x/i' =>  'Mac OS X',
                '/mac_powerpc/i'        =>  'Mac OS 9',
                '/linux/i'              =>  'Linux',
                '/ubuntu/i'             =>  'Ubuntu',
                '/iphone/i'             =>  'iPhone',
                '/ipod/i'               =>  'iPod',
                '/ipad/i'               =>  'iPad',
                '/android/i'            =>  'Android',
                '/blackberry/i'         =>  'BlackBerry',
                '/webos/i'              =>  'Mobile'
            );
        
            foreach ( $os_array as $regex => $value ) { 
                if ( preg_match($regex, $user_agent ) ) {
                    $os_platform = $value;
                }
            }   
            return $os_platform;
        }
        
        public function getUserBrowser() {
            $user_agent = $_SERVER['HTTP_USER_AGENT'];
        
            $browser        = "Bilinmeyen Tarayıcı";
            $browser_array  = array(
                '/msie/i'       =>  'Internet Explorer',
                '/firefox/i'    =>  'Firefox',
                '/safari/i'     =>  'Safari',
                '/chrome/i'     =>  'Chrome',
                '/edge/i'       =>  'Edge',
                '/opera/i'      =>  'Opera',
                '/netscape/i'   =>  'Netscape',
                '/maxthon/i'    =>  'Maxthon',
                '/konqueror/i'  =>  'Konqueror',
                '/mobile/i'     =>  'Handheld Browser'
            );
        
            foreach ( $browser_array as $regex => $value ) { 
                if ( preg_match( $regex, $user_agent ) ) {
                    $browser = $value;
                }
            }
            return $browser;
        }

        public function getUserAgent() {
            if(!empty($_SERVER['HTTP_USER_AGENT'])) {
                return $_SERVER['HTTP_USER_AGENT'];
            }
            return "No value";
        }

        public function slugify($string, $separator = '-', $css_mode = false){
            if ($separator === true || $separator === false) {
                $css_mode = $separator;
                $separator = '-';
                trigger_error('utils::slugify() now takes $css_mode as the third parameter, please update your code', E_USER_DEPRECATED);
            }

            $slug = preg_replace('/([^a-z0-9]+)/', $separator, strtolower($string));
            if($css_mode) {
                $digits = array('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine');
                if (is_numeric(substr($slug, 0, 1))) {
                    $slug = $digits[substr($slug, 0, 1)] . substr($slug, 1);
                }
            }

            return $slug;
        }

        public function randomString($length = 10) {
            $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $charactersLength = strlen($characters);
            $randomString = '';
            for ($i = 0; $i < $length; $i++) {
                $randomString .= $characters[rand(0, $charactersLength - 1)];
            }
            return $randomString;
        }

        public function isUserExists($email){
            $query = $this->db->query("SELECT id FROM {$this->db->prefix}users WHERE email = :email", array(':email'=>$email));
            if($query->num_rows > 0) {
                return true;
            }
            return false;
        }

        public function addResetTicket($email){
            $token = bin2hex(random_bytes(16));
            try {
                $this->db->query("INSERT INTO {$this->db->prefix}resettickets (`email`, `token`, `expires`, `used`) VALUES (:email, :token, DATE_ADD(NOW(), INTERVAL 1 DAY), 0)", array(':email'=>$email, ':token'=>$token));
            } catch (PDOException $e) {
                return false;
            }
            return $token;
        }

        public function errorLog($type, $message, $user_id, $request_uri){
            $this->db->query("INSERT INTO {$this->db->prefix}logs (`type`, `message`, `user_id`, `request_uri`, `date`) VALUES (:type,:message,:user_id,:request_uri,NOW())", array(":type"=>$type,":message"=>$message, ":user_id"=>$user_id, ":request_uri"=>$request_uri));
        }

        public function getMenuItems($data = array()) {
            $menu = array();
            $sub_items = array();
            $sql = "SELECT id, title, link, parent, icon, col, class FROM {$this->db->prefix}menu WHERE status=1 AND parent=0";
            
            if(isset($data['position'])){
                $sql .= " AND position = '{$data['position']}'";
            }

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

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

            $query = $this->db->query($sql);
            
            if($query->num_rows > 0) {       
                foreach($query->rows as $row){
                    $sub_items = $this->getSubMenuItems($data, $row["id"]);
                    $item = array(
                        'id'                     => $row["id"],
                        'title'                  => $row["title"],
                        'link'                   => $row["link"],
                        'icon'                   => $row["icon"],
                        'col'                    => $row["col"],
                        'class'                  => $row["class"],
                        'sub_items'              => empty($sub_items) ? "" : $sub_items
                    );
                    array_push($menu, $item);
                }
            }
            return $menu;
        }

        public function getSubMenuItems($data = array(), $parent) {
            $menu = array();
            $sql = "SELECT id, title, link, parent, icon, col, class FROM {$this->db->prefix}menu WHERE status=1 AND parent=:parent";
            
            if(isset($data['position'])){
                $sql .= " AND position = '{$data['position']}'";
            }

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

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

            $query = $this->db->query($sql, array(':parent'=>$parent));
            if($query->num_rows > 0) {
                foreach($query->rows as $row){
                    $item = array(
                        'id'                     => $row["id"],
                        'title'                  => $row["title"],
                        'link'                   => $row["link"],
                        'icon'                   => $row["icon"],
                        'col'                    => $row["col"],
                        'class'                  => $row["class"]
                    );
                    array_push($menu, $item);
                }
                
            }
            return $menu;
        }

        public function getInfoText($text){
            $query = $this->db->query( "SELECT d.title, d.description FROM {$this->db->prefix}information_description d LEFT JOIN {$this->db->prefix}information i ON i.information_id = d.id WHERE i.status = 1 AND i.type = :type LIMIT 1", array(':type'=>$text) );
            if($query->num_rows > 0) {
                $result = array('title'=>$query->row['title'], 'description'=>$query->row['description']);
                return $result;
            }
            return false;
        }

        public function getContentInfoText($id){
            $query = $this->db->query( "SELECT c.title, c.description, (SELECT url FROM {$this->db->prefix}urls WHERE element=c.id AND url_type='page') AS 'url' FROM {$this->db->prefix}pages c WHERE c.status = 1 AND c.id = :id LIMIT 1", array(':id'=>$id) );
            if($query->num_rows > 0) {
                $result = array('title'=>$query->row['title'], 'description'=>$query->row['description'], 'url'=>$query->row['url']);
                return $result;
            }
            return false;
        }

        public function getCities(){
            $cities = array();
            $query = $this->db->query("SELECT plate_no, name FROM {$this->db->prefix}cities ORDER BY name ASC");
            if($query->num_rows > 0) {
                foreach($query->rows as $row){
                    $item = array(
                        'plate_no'      => $row["plate_no"], 
                        'name'         => $row["name"]
                    );
                    array_push($cities, $item);
                }
            }
            return $cities;
        }

        public function getTowns($city_id){
            $towns = array();
            $stmt = $this->db->query( "SELECT t.id, t.name FROM {$this->db->prefix}towns t LEFT JOIN {$this->db->prefix}cities c ON c.id=t.city_id WHERE c.plate_no=:plate_no ORDER BY t.name ASC", array(":plate_no"=>$city_id));
            if($stmt->num_rows > 0) {
                foreach($stmt->rows as $row){
                    $item = array(
                        'id'           => $row["id"], 
                        'name'         => $row["name"]
                    );
                    array_push($towns, $item);
                }
            }
            return $towns;
        }

        public function getCityName($plate_no){
            $stmt = $this->db->query("SELECT name FROM {$this->db->prefix}cities WHERE plate_no = :plate_no", array(':plate_no'=>(int)$plate_no));
            if ($stmt->num_rows > 0) {
                return $stmt->row['name'];
            }
            return '';
        }

        public function getTownName($town_id){
            $stmt = $this->db->query("SELECT name FROM {$this->db->prefix}towns WHERE id = :id", array(':id'=>(int)$town_id));
            if ($stmt->num_rows > 0) {
                return $stmt->row['name'];
            }
            return '';
        }

        public function getFAQ($data = array()){
            $faq = array();
            $query = "SELECT id, question, answer, keywords, featured FROM {$this->db->prefix}faq WHERE status=1";
            if(isset($data['search_keywords'])){
                if($data['search_keywords'] != ''){
                    $keywords = explode(' ', $data['search_keywords']);
                    $searchTermKeywords = array();
                    foreach ($keywords as $word) 
                    {
                        $word                 = $this->db->escape($word);
                        $searchTermKeywords[] = "((question LIKE '%$word%') OR (keywords LIKE '%$word%'))";
                    }
                    $query .= ' AND '.implode(' AND ', $searchTermKeywords);
                }
            }

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

            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){                    
                    $item = array(
                        'id'            => $row['id'], 
                        'question'      => $row['question'], 
                        'answer'        => $row['answer'],  
                        'keywords'      => $row['keywords'], 
                        'featured'      => $row['featured']
                    );
                    array_push($faq, $item);
                }
            }
            return $faq;
        }

        public function getFaqCategories(){
            $faq = array();
            $query = "SELECT f.id, f.title, icon, f.description, u.url FROM {$this->db->prefix}faq_categories f LEFT JOIN {$this->db->prefix}urls u ON u.element=f.id WHERE status=1 AND url_type='faq-category' ORDER BY f.id ASC";
            $stmt = $this->db->query($query);
            if($stmt->num_rows > 0) {
                foreach($stmt->rows as $row){                    
                    $item = array(
                        'id'            => $row['id'], 
                        'title'         => $row['title'], 
                        'description'   => $row['description'],  
                        'icon'          => $row['icon'], 
                        'url'           => $row['url']
                    );
                    array_push($faq, $item);
                }
            }
            return $faq;
        }

        public function getTestimonials($data = array()){
            $testimonials = array();
            $query = "SELECT id, image, name, title, text FROM {$this->db->prefix}testimonials WHERE status=1";
            if(isset($data['search_keywords'])){
                if($data['search_keywords'] != ''){
                    $keywords = explode(' ', $data['search_keywords']);
                    $searchTermKeywords = array();
                    foreach ($keywords as $word) {
                        $word                 = $this->db->escape($word);
                        $searchTermKeywords[] = "((name LIKE '%$word%') OR (title 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){                    
                    $item = array(
                        'id'            => $row['id'], 
                        'image'         => $row['image'], 
                        'name'          => $row['name'],  
                        'title'         => $row['title'], 
                        'text'          => $row['text']
                    );
                    array_push($testimonials, $item);
                }
            }
            return $testimonials;
        }

        public function getBankAccounts(){
            $bank_accounts = array();
            $stmt = $this->db->conn->prepare( "SELECT a.id, a.owner, a.iban, a.branch, a.account_number, b.name AS 'bank_name', b.image AS 'bank_image' FROM {$this->db->prefix}bank_accounts a LEFT JOIN {$this->db->prefix}banks b ON b.id=a.bank_id WHERE a.status=1" );
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result($id, $owner, $iban, $branch, $account_number, $bank_name, $bank_image);
            if($stmt->num_rows > 0) {
                while($stmt->fetch()){                    
                    $item = array(
                        'id'            => $id, 
                        'owner'         => $owner, 
                        'iban'          => $iban,  
                        'branch'        => $branch, 
                        'account_number'=> $account_number, 
                        'bank_name'     => $bank_name, 
                        'bank_image'    => $bank_image
                    );
                    array_push($bank_accounts, $item);
                }
            }
            $stmt->close();
            return $bank_accounts;
        }

        /* URL Operations */
        public function generateUrl($s, $prefix="", $i=0) {
            $tr = array('ş','Ş','ı','I','İ','ğ','Ğ','ü','Ü','ö','Ö','Ç','ç');
            $eng = array('s','s','i','i','i','g','g','u','u','o','o','c','c');

            do {
                $generated_url = str_replace($tr,$eng,$s);
                $generated_url = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $generated_url), '-'));

                if($i != 0){
                    $generated_url = $generated_url."-".$i;
                }
                $generated_url = $prefix.$generated_url;
                $i++;
            }while(!$this->isUrlExists($generated_url));

            return $generated_url;
        }
        function isUrlExists($generated_url){
            $stmt = $this->db->query( "SELECT id FROM {$this->db->prefix}urls WHERE url = :url limit 1", array(':url' => $generated_url));
            if($stmt->num_rows == 0) {
                return true;
            }
            return false;
        }
        public function addUrl($url, $url_type, $element, $route, $meta_title="", $meta_description=""){
            $stmt = $this->db->query("INSERT INTO {$this->db->prefix}urls (`url`, `url_type`, `element`, `route`, `title`, `description`, login) VALUES (:url, :url_type, :element, :route, :title, :description, 1)", array(':url'=>$url, ':url_type'=>$url_type, ':element'=>$element, ':route'=>$route, ':title'=>$meta_title,  ':description'=>$meta_description));
            if ($stmt->error) {
                $this->errorLog("error", "Cannot add url. Error: ".$stmt->error_info['message'], 0, $_SERVER['REQUEST_URI']);
            }
        }
        function getUrlId($url){
            $stmt = $this->db->query("SELECT id FROM {$this->db->prefix}urls WHERE url = :url LIMIT 1", array(':url'=>$url));
            if($stmt->num_rows > 0) {
                return true;
            }
            return false;
        }
        function updateUrl($url_type, $element, $title, $description){
            $stmt = $this->db->query("UPDATE {$this->db->prefix}urls SET title=:title, description=:description WHERE url_type=:url_type, element=:element", array(':url_type'=>$url_type, ':element'=>$element, ':title'=>$title, ':description'=>$description));
            if ($stmt->error) {
                $this->errorLog("error", "Cannot update url. Error: ".$stmt->error_info['message'], 0, $_SERVER['REQUEST_URI']);
            }
        }
        function deleteUrl($element, $url_type){
            $this->db->query("DELETE FROM {$this->db->prefix}urls WHERE element=:element AND url_type=:url_type", array(':element'=>$element, ':url_type'=>$url_type));
        }

        public function getItemURL($element, $url_type){
            $stmt = $this->db->query("SELECT * FROM {$this->db->prefix}urls WHERE element=:element AND url_type=:url_type", array(':element'=>$element, ':url_type'=>$url_type));
            if($stmt->num_rows > 0) {
                return $stmt->row;
            }
            return null;
        }

        function getItemIdFromUrl($url){
            $stmt = $this->db->conn->prepare( "SELECT element FROM {$this->db->prefix}urls WHERE url = ? LIMIT 1");
            $stmt->bind_param("s", $url);
            $stmt->execute();
            $stmt->bind_result($element);
            $stmt->store_result();
            $stmt->fetch();
            if($stmt->num_rows > 0) {
                $stmt->close();
                return $element;
            }
            return false;
        }

        /* URL Operations */
        public function moneyFormatter($number){
            $fmt 		= numfmt_create( 'tr_TR', NumberFormatter::CURRENCY );
            $money		= numfmt_format_currency($fmt, $number, "TRY");
            $money 		= preg_replace( '/[^0-9,"."]/', '', $money );
            return $money;
        }

        public function dateFormatter($date){
            $phpdate = strtotime( $date );
            $mysqldate = date( 'd M Y', $phpdate );
            return $mysqldate;
        }

        public function UTCToLocalDate($utc){
            $dt = new DateTime($utc);
            $tz = new DateTimeZone('Europe/Istanbul');

            $dt->setTimezone($tz);
            return $dt->format('Y-m-d H:i:s');
        }

        public function secToTime($seconds){
            $hours = floor($seconds / 3600);
            $mins = floor($seconds / 60 % 60);
            $secs = floor($seconds % 60);
            $timeFormat = sprintf('%02d:%02d:%02d', $hours, $mins, $secs);

            return $timeFormat;
        }

        public function pagination($total_pages, $visible=10, $page=1){
            $adjacents = "2"; 
            $prevlabel = "Önceki";
            $nextlabel = "Sonraki";
            $lastlabel = "&rsaquo;&rsaquo;";
        
            $page = ($page == 0 ? 1 : $page); 
            $start = ($page - 1) * $visible;                               
            $prev = $page - 1; 
            $next = $page + 1;
        
            $lastpage = ceil($total_pages/$visible);
            $lpm1 = $lastpage - 1;
            $pagination = "";
        
            if($lastpage > 1){   
                if ($page > 1){
                    $pagination.= "<li class='page-item'><a href='#' class='page-link prev' data-page='{$prev}' aria-label=\"önceki sayfaya git\"><i class='bi bi-chevron-left' aria-hidden='true'></i></a></li>";
                }else{
                    $pagination.= "<li class='page-item'><a href='#' class='page-link prev disabled' aria-label=\"önceki sayfaya git\"><i class='bi bi-chevron-left' aria-hidden='true'></i></a></li>";
                }
                if ($lastpage < 7 + ($adjacents * 2)){   
                    for ($counter = 1; $counter <= $lastpage; $counter++){
                        if ($counter == $page)
                            $pagination.= "<li class='page-item active'><a href='javascript:;' class='page-link' aria-label=\"Geçerli sayfa, {$counter}. sayfa\" aria-current=\"true\">{$counter}</a></li>";
                        else
                            $pagination.= "<li class='page-item'><a href='#' class='page-link' data-page='{$counter}' aria-label=\"{$counter}. sayfaya git\">{$counter}</a></li>";                    
                    }
                } else if($lastpage > 5 + ($adjacents * 2)){
                    if($page < 1 + ($adjacents * 2)) {
                        for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++){
                            if ($counter == $page)
                                $pagination.= "<li class='page-item active'><a href='javascript:;' class='page-link' aria-label=\"Geçerli sayfa, {$counter}. sayfa\" aria-current=\"true\">{$counter}</a></li>";
                            else
                                $pagination.= "<li class='page-item'><a href='#' class='page-link' data-page='{$counter}' aria-label=\"{$counter}. sayfaya git\">{$counter}</a></li>";                    
                        }
                        $pagination.= "<li class='page-item'><a href='javascript:;' class='page-link'>...</a></li>";
                        $pagination.= "<li class='page-item'><a href='#' class='page-link' data-page='{$lpm1}' aria-label=\"{$lpm1}. sayfaya git\">{$lpm1}</a></li>";
                        $pagination.= "<li class='page-item'><a href='#' class='page-link' data-page='{$lastpage}' aria-label=\"{$lastpage}. sayfaya git\">{$lastpage}</a></li>";  
                    } else if($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) {
                        $pagination.= "<li class='page-item'><a href='#' class='page-link' data-page='{1}' aria-label=\"1. sayfaya git\">1</a></li>";
                        $pagination.= "<li class='page-item'><a href='#' class='page-link' data-page='2' aria-label=\"2. sayfaya git\">2</a></li>";
                        $pagination.= "<li class='page-item'><a href='javascript:;' class='page-link' aria-label=\"ara sayfalar\">...</a></li>";
                        for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++) {
                            if ($counter == $page)
                                $pagination.= "<li class='page-item active'><a href='javascript:;' class='page-link' aria-label=\"Geçerli sayfa, {$counter}. sayfa\" aria-current=\"true\">{$counter}</a></li>";
                            else
                                $pagination.= "<li class='page-item'><a href='#' class='page-link' data-page='{$counter}' aria-label=\"{$counter}. sayfaya git\">{$counter}</a></li>";                    
                        }
                        $pagination.= "<li class='page-item'><a href='javascript:;' class='page-link' aria-label=\"ara sayfalar\">...</a></li>";
                        $pagination.= "<li class='page-item'><a href='#' class='page-link' data-page='{$lpm1}' aria-label=\"{$lpm1}. sayfaya git\">{$lpm1}</a></li>";
                        $pagination.= "<li class='page-item'><a href='#' class='page-link' data-page='{$lastpage}' aria-label=\"{$lastpage}. sayfaya git\">{$lastpage}</a></li>";      
                    } else {
                        $pagination.= "<li class='page-item'><a href='#' class='page-link' data-page='1' aria-label=\"1. sayfaya git\">1</a></li>";
                        $pagination.= "<li class='page-item'><a href='#' class='page-link' data-page='2' aria-label=\"2. sayfaya git\">2</a></li>";
                        $pagination.= "<li class='page-item'><a href='javascript:;' class='page-link' aria-label=\"ara sayfalar\">...</a></li>";
                        for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++) {
                            if ($counter == $page)
                                $pagination.= "<li class='page-item active'><a href='javascript:;' class='page-link' aria-label=\"Geçerli sayfa, {$counter}. sayfa\" aria-current=\"true\">{$counter}</a></li>";
                            else
                                $pagination.= "<li class='page-item'><a href='#' class='page-link' data-page='{$counter}' aria-label=\"{$counter}. sayfaya git\">{$counter}</a></li>";                    
                        }
                    }
                }
                if ($page < $counter - 1){
                    $pagination.= "<li class='page-item'><a href='#' class='page-link next' data-page='{$next}' aria-label=\"sonraki sayfaya git\"><i class='bi bi-chevron-right' aria-hidden='true'></i></a></li>";
                }else{
                    $pagination.= "<li class='page-item'><a href='#' class='page-link next disabled' aria-label=\"sonraki sayfaya git\"><i class='bi bi-chevron-right' aria-hidden='true'></i></a></li>";
                }
            }
            return $pagination;
        }

        public function createRatingStars($rating){
            if($rating < 0){
                $rating = 0;
            }
            if($rating > 5){
                $rating = 5;
            }
            $html = "";
            for($i=0; $i<round($rating); $i++){
                $html   .='<span class="bi bi-star-fill"></span>';
            }
            for($i=0; $i<5-round($rating); $i++){
                $html   .='<span class="bi bi-star"></span>';
            }
            return $html;
        }

        public function getOption($option){
            $option = trim($option);
            if(empty($option)){
                return false;
            }
            $values = array();
            $query = $this->db->query( "SELECT value FROM {$this->db->prefix}options WHERE name=:name ORDER BY id ASC", array(":name"=>$option));
            if($query->num_rows == 1) {
                $value = $query->row["value"];
                if($this->isJSON($value)){
                    $type = $this->getJSONType($value);
                    if($type == 'object'){
                        $values = array(json_decode($value, true));
                    }else if($type == 'array'){
                        $values = json_decode($value, true);
                    }
                }else{
                    $values = array(
                        'value'      => $value
                    );
                }
            }else if($query->num_rows > 1) {
                foreach($query->rows as $row){    
                    $value = $row["value"];
                    if($this->isJSON($value)){
                        $type = $this->getJSONType($value);
                        if($type == 'object'){
                            $item = json_decode($value, true);
                        }else if($type == 'array'){
                            foreach(json_decode($value, true) as $key => $row){
                                array_push($values, $row);
                            }
                            continue;
                        }
                    }else{
                        $item = array(
                            'value'      => $value
                        );
                    }
                    array_push($values, $item);
                }
            }
            return $values;
        }

        public function setOption($key, $value) {
            $stmt = $this->db->query("UPDATE {$this->db->prefix}options SET `value`=:value WHERE `name`=:name",array(':value'=>$value, ':name'=>$key));
            if($stmt->error){
                $this->errorLog("error", "Cannot update option. Error: ".$stmt->error_info['message'], 0, $_SERVER['REQUEST_URI']);
                return false;
            }else{
                return true;
            }
        }

        public function isJSON($string) {
            json_decode($string);
            return (json_last_error()===JSON_ERROR_NONE);
        }

        public function getJSONType($json) {
            $obj = json_decode($json);
            $json = ltrim($json);

            if ($obj === null) {
                return false; // Not valid JSON
            }
            if (strpos($json, '{') === 0) {
                return 'object'; // Object
            }
            if (strpos($json, '[') === 0) {
                return 'array'; // Array
            }
        
            return false;
        }

        public function createPdf($content, $location){
            $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
            $pdf->setPrintHeader(false);
            $pdf->setPrintFooter(false);
            $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
            $pdf->SetMargins(PDF_MARGIN_LEFT, 15, PDF_MARGIN_RIGHT);
            $pdf->SetAutoPageBreak(TRUE, 15);
            $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

            $pdf->setFontSubsetting(true);
            $pdf->SetFont('times', '', 12);
            $pdf->AddPage();
            
            $pdf->writeHTML($content, true, false, true, false, '');

            $pdf->lastPage();
            $pdf->Output($location, 'F');

            /*$pdf = new PDF('P','mm','A4');
            $pdf->SetAutoPageBreak(true, 15);
            $pdf->AddPage();
            $pdf->AddFont('Arial','','arial.php');
            $pdf->SetFont('Arial', '', 10);

            $content = iconv('utf-8', 'ISO-8859-9', $content);
            $pdf->WriteHTML($content);

            $pdf->Output($location, 'F');*/
        }

        public function getUserByResetToken($token){
            $stmt = $this->db->query("SELECT email FROM {$this->db->prefix}resettickets WHERE token = :token", array(':token'=>$token));
            if ($stmt->num_rows > 0) {
                return $stmt->row["email"];
            }
            return '';
        }

        public function strtolower_tr($text){
            $bul 	= array("I","Ğ","Ü","Ş","İ","Ö","Ç");
            $degis  = array("ı","ğ","ü","ş","i","ö","ç");
            $text	= str_replace($bul, $degis, $text);
            $text	= strtolower($text);
            return $text;
        }

        public function getBanners($pos = 1){
            $banners = array();
            $query = $this->db->query("SELECT `id`, `status`, `title`, `link`, `image`, `order`, `pos` FROM {$this->db->prefix}banners WHERE pos=:pos AND status=1 ORDER BY `order` ASC", array(':pos'=>$pos));
            if($query->num_rows > 0) {
                foreach($query->rows as $row){
                    $item = array(
                        'id'      => $row["id"], 
                        'status'         => $row["status"],
                        'title'          => $row["title"],
                        'link'           => $row["link"],
                        'image'          => $row["image"],
                        'order'          => $row["order"],
                        'pos'            => $row["pos"]
                    );
                    array_push($banners, $item);
                }
            }
            return $banners;
        }

        public function generateGuid(){
            if (function_exists('com_create_guid') === true) {
                return trim(com_create_guid(), '{}');
            }
        
            return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
        }

        public function is_in_array($array, $key, $key_value){
            $within_array = false;
            foreach( $array as $k=>$v ){
                if( is_array($v) ){
                    $within_array = $this->is_in_array($v, $key, $key_value);
                    if( $within_array == true){
                        break;
                    }
                } else {
                    if( $v == $key_value && $k == $key ){
                        $within_array = true;
                        break;
                    }
                }
            }
            return $within_array;
        }

        public function resizeCropImage($max_width, $max_height, $source_file, $dst_dir, $quality = 80){
            $imgsize     = getimagesize($source_file);
            $width       = $imgsize[0];
            $height      = $imgsize[1];
            $mime        = $imgsize['mime'];
         
            $dst_img = imagecreatetruecolor($max_width, $max_height);
            switch($mime){
                case 'image/gif':
                    $image_create = "imagecreatefromgif";
                    $result = "imagegif";
                    break;
                case 'image/png':
                    $image_create = "imagecreatefrompng";
                    $result = "imagepng";
                    $quality = round((100 - $quality) * 0.09);
                    $background = imagecolorallocate($dst_img , 0, 0, 0);
                    imagecolortransparent($dst_img, $background);
                    imagealphablending($dst_img, false);
                    break;
                case 'image/jpeg':
                    $image_create = "imagecreatefromjpeg";
                    $result = "imagejpeg";
                    break;
                case 'image/webp':
                    $image_create = "imagecreatefromwebp";
                    $result = "imagewebp";
                    break;
                default:
                    return false;
                    break;
            }
             
            $src_img = $image_create($source_file);
            
            $src_w = imagesx($src_img);
            $src_h = imagesy($src_img);
        
            if($src_w > $src_h){
                $dst_w = $max_width;
                $dst_h = ($dst_w * $src_h) / $src_w ;
        
                if($dst_h > $max_height){
                    $dst_h = $max_height;
                    $dst_w = ($dst_h * $src_w) / $src_h;
                }
            }else{
                $dst_h = $max_height;
                $dst_w = ($dst_h * $src_w) / $src_h;
        
                if($dst_w > $max_width){
                    $dst_w = $max_width;
                    $dst_h = ($dst_w * $src_h) / $src_w;
                }
            }
        
            $dst_x = abs($max_width - $dst_w) / 2;
            $dst_y = abs($max_height - $dst_h) / 2;
        
            $color = imagecolorallocatealpha($dst_img, 0, 0, 0, 127); //fill transparent background
            if ($mime != 'image/png') {
                $color = imagecolorallocatealpha($dst_img, 255, 255, 255, 0); //fill white background
            }
            imagefill($dst_img, 0, 0, $color);
            imagesavealpha($dst_img, true);
            imagecopyresampled($dst_img, $src_img, $dst_x, $dst_y,0,0, $dst_w, $dst_h, $src_w, $src_h);
            $result($dst_img, $dst_dir, $quality);
            if($dst_img)imagedestroy($dst_img);
            if($src_img)imagedestroy($src_img);
        }

        public function createWebpImage($max_width, $max_height, $source_file, $dst_dir, $quality = 80){
            $imgsize     = getimagesize($source_file);
            $width       = $imgsize[0];
            $height      = $imgsize[1];
            $mime        = $imgsize['mime'];
         
            $dst_img = imagecreatetruecolor($max_width, $max_height);
            switch($mime){
                case 'image/gif':
                    $image_create = "imagecreatefromgif";
                    $result = "imagegif";
                    break;
                case 'image/png':
                    $image_create = "imagecreatefrompng";
                    $result = "imagepng";
                    $quality = round((100 - $quality) * 0.09);
                    $background = imagecolorallocate($dst_img , 0, 0, 0);
                    imagecolortransparent($dst_img, $background);
                    imagealphablending($dst_img, false);
                    break;
                case 'image/jpeg':
                    $image_create = "imagecreatefromjpeg";
                    $result = "imagejpeg";
                    break;
                case 'image/webp':
                    $image_create = "imagecreatefromwebp";
                    $result = "imagewebp";
                    break;
                default:
                    return false;
                    break;
            }
             
            $src_img = $image_create($source_file);
            
            $src_w = imagesx($src_img);
            $src_h = imagesy($src_img);
        
            if($src_w > $src_h){
                $dst_w = $max_width;
                $dst_h = ($dst_w * $src_h) / $src_w ;
        
                if($dst_h > $max_height){
                    $dst_h = $max_height;
                    $dst_w = ($dst_h * $src_w) / $src_h;
                }
            }else{
                $dst_h = $max_height;
                $dst_w = ($dst_h * $src_w) / $src_h;
        
                if($dst_w > $max_width){
                    $dst_w = $max_width;
                    $dst_h = ($dst_w * $src_h) / $src_w;
                }
            }
        
            $dst_x = abs($max_width - $dst_w) / 2;
            $dst_y = abs($max_height - $dst_h) / 2;
        
            $color = imagecolorallocatealpha($dst_img, 0, 0, 0, 127); //fill transparent background
            if ($mime != 'image/png') {
                $color = imagecolorallocatealpha($dst_img, 255, 255, 255, 0); //fill white background
            }
            imagefill($dst_img, 0, 0, $color);
            imagesavealpha($dst_img, true);
            imagecopyresampled($dst_img, $src_img, $dst_x, $dst_y,0,0, $dst_w, $dst_h, $src_w, $src_h);
            $result($dst_img, $dst_dir, $quality);
            if($dst_img)imagedestroy($dst_img);
            if($src_img)imagedestroy($src_img);
        }
    }