<?php
    class User {
        protected $db;
        protected $utils;
        protected $session;

        public function __construct(Database $db, Utils $utils, Session $session){
            $this->db = $db;
            $this->utils = $utils;
        }

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

            if(isset($data['in'])){
                if($data['in'] != ''){
                    $query .= " AND id IN (".$data['in'].")";
                }
            }

            if(isset($data['search_keywords']) && !empty($data['search_keywords'])){
                $keywords = explode(' ', trim($data['search_keywords']));
                $searchTermKeywords = array();
                foreach ($keywords as $word) {
                    $word                 = $this->db->escape($word);
                    $searchTermKeywords[] = "(firstname LIKE '%$word%' OR lastname LIKE '%$word%' OR email LIKE '%$word%' OR phone 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';
                    }
                    $row['status_id'] = $row['status'];
                    $row['status'] = $status;
                    $row['orders'] = $this->getUserOrderCount($row['id']);
                    array_push($users, $row);
                }
            }
            
            return $users;
        }

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

            if(isset($data['in'])){
                if($data['in'] != ''){
                    $query .= " AND id IN (".$data['in'].")";
                }
            }

            if(isset($data['search_keywords']) && !empty($data['search_keywords'])){
                $keywords = explode(' ', trim($data['search_keywords']));
                $searchTermKeywords = array();
                foreach ($keywords as $word) {
                    $word                 = $this->db->escape($word);
                    $searchTermKeywords[] = "(firstname LIKE '%$word%' OR lastname LIKE '%$word%' OR email LIKE '%$word%' OR phone 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 getUser($user_id) {
            $user_details = array();
            $query = "SELECT * FROM {$this->db->prefix}users WHERE id=:user_id LIMIT 1";
            
            $stmt = $this->db->query($query, array(':user_id'=>$user_id));
            if($stmt->num_rows > 0) {
                $user_details = $stmt->row;
            }

            return $user_details;
        }

        public function getUserOrderCount($user_id) {
            $total = 0;
            $query = "SELECT COUNT(o.id) AS 'total' FROM {$this->db->prefix}users u LEFT JOIN {$this->db->prefix}orders o ON o.user_id=u.id WHERE u.id=:user_id";
            
            $stmt = $this->db->query($query, array(':user_id'=>$user_id));
            if($stmt->num_rows > 0) {
                $total = $stmt->row['total'];
            }

            return $total;
        }

        public function getAdresses($data = array()){
            $address_arr = array();
            $query = "SELECT a.id, a.status, a.type, a.title, firstname, lastname, tckno, company, tax_no, tax_office, a.city, a.town, address, phone, isdefault, c.name AS 'city_name', t.name AS 'town_name' FROM {$this->db->prefix}address a LEFT JOIN {$this->db->prefix}cities c ON c.plate_no = a.city LEFT JOIN {$this->db->prefix}towns t ON t.id = a.town WHERE a.user_id = :user_id";

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

            if(isset($data['status'])){
                if($data['status'] != 0){
                    $query .= " AND a.status =".$data['status'];
                }
            }
            if(isset($data['default'])){
                if($data['default'] != 0){
                    $query .= " AND a.isdefault = 1";
                }
            }

            if(isset($data['keyword']) && $data['keyword'] != ""){
                $query .= " AND a.title LIKE '{$data['keyword']}%'";
            }

            if(isset($data['sort'])){
                $query .= " ORDER BY a." . $data['sort'];
            }else{
                $query .= " ORDER BY a.id";
            }
    
            if(isset($data['order'])){
                $query .= " ".$data['order'];
            }else{
                $query .= " ASC";
            }
    
            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, array(':user_id'=>$data['user_id']));
            if($stmt->num_rows > 0){
                foreach($stmt->rows as $row){
                    $item = array(
                        'id'            => $row['id'],
                        'status'        => $row['status'],
                        'type'          => $row['type'],
                        'title'         => $row['title'],
                        'firstname'     => $row['firstname'],
                        'lastname'      => $row['lastname'],
                        'tckno'         => $row['tckno'],
                        'company'       => $row['company'],
                        'tax_no'        => $row['tax_no'],
                        'tax_office'    => $row['tax_office'],
                        'city'          => $row['city'],
                        'town'          => $row['town'],
                        'address'       => $row['address'],
                        'phone'         => $row['phone'],
                        'default'       => $row['isdefault'],
                        'city_name'     => $row['city_name'],
                        'town_name'     => $row['town_name']
                    );
                    array_push($address_arr, $item);
                }
            }

            return $address_arr;
        }

        public function getAdress($address_id){
            $query = "SELECT a.id, a.status, a.type, a.title, firstname, lastname, tckno, company, tax_no, tax_office, a.city, a.town, address, phone, isdefault, c.name AS 'city_name', t.name AS 'town_name' FROM {$this->db->prefix}address a LEFT JOIN {$this->db->prefix}cities c ON c.plate_no = a.city LEFT JOIN {$this->db->prefix}towns t ON t.id = a.town WHERE a.id = :id LIMIT 1";

            $stmt = $this->db->query($query, array(':id'=>$address_id));
            if($stmt->num_rows > 0) {
                $result = array(
                    'id'            => $stmt->row['id'],
                    'status'        => $stmt->row['status'],
                    'type'          => $stmt->row['type'],
                    'title'         => $stmt->row['title'],
                    'firstname'     => $stmt->row['firstname'],
                    'lastname'      => $stmt->row['lastname'],
                    'tckno'         => $stmt->row['tckno'],
                    'company'       => $stmt->row['company'],
                    'tax_no'        => $stmt->row['tax_no'],
                    'tax_office'    => $stmt->row['tax_office'],
                    'city'          => $stmt->row['city'],
                    'town'          => $stmt->row['town'],
                    'address'       => $stmt->row['address'],
                    'phone'         => $stmt->row['phone'],
                    'default'       => $stmt->row['isdefault'],
                    'city_name'     => $stmt->row['city_name'],
                    'town_name'     => $stmt->row['town_name']
                );
    
                return $result;
            }
            return array();
        }

        public function changeDefaultAddress($address_id, $user_id){
            $stmt = $this->db->query("UPDATE {$this->db->prefix}address SET `isdefault`=0 WHERE id != :id AND `user_id`=:user_id", array(':id'=>$address_id, ':user_id'=>$user_id));
            if ($stmt->error) {
                $this->utils->errorLog("error", "Cannot change default address. AddressId: {$address_id} Error: {$stmt->error_info}", $user_id, $_SERVER['REQUEST_URI']);
                return false;
            }
        }

        public function getUserEmail($user_id){
            $stmt = $this->db->query("SELECT email FROM ".$this->db->prefix."users WHERE id = :id LIMIT 1", array(':id'=>$user_id));
            if ($stmt->num_rows > 0) {
                return $stmt->row['email'];
            }
            return "";
        }

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

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