<?php
    class CouponCodes {

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

        public function getCodes($data = array()) {
            $rows = array();
            $query = "SELECT * FROM {$this->db->prefix}coupon_codes WHERE 1";

            if(isset($data['search_keywords']) && $data['search_keywords'] != ""){
                $keywords = explode(' ', $data['search_keywords']);
                $searchTermKeywords = array();
                foreach ($keywords as $word) {
                    $word                 = $this->db->escape($word);
                    $searchTermKeywords[] = "(code LIKE '%$word%' OR title LIKE '%$word%' OR description LIKE '%$word%')";
                }
                $query .= ' AND '.implode(' AND ', $searchTermKeywords);
            }

            if(isset($data['status']) && $data['status'] != ""){
                $query .= " AND status='" . (int)$data['status'] . "'";
            }

            if(isset($data['type']) && $data['type'] != ""){
                $query .= " AND type='" . (int)$data['type'] . "'";
            }

            if(isset($data['discount_type']) && $data['discount_type'] != ""){
                $query .= " AND discount_type='" . (int)$data['discount_type'] . "'";
            }
            
            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'],
                        'status'                 => $row['status'],
                        'title'                  => $row['title'],
                        'description'            => $row['description'],
                        'code'                   => $row['code'],
                        'type'                   => $row['type'],
                        'discount_type'          => $row['discount_type'],
                        'discount'               => $row['discount'],
                        'minimum_total'          => $row['minimum_total'],
                        'date_start'             => $row['date_start'],
                        'date_end'               => $row['date_end'],
                        'date_added'             => $row['date_added'],
                        'date_issued'            => $row['date_issued']
                    );
                    array_push($rows, $item);
                }
            }
            return $rows;
        }

        public function getTotalCodes($data = array()) {
            $total_rows = array();
            $query = "SELECT COUNT(id) AS 'total' FROM {$this->db->prefix}coupon_codes WHERE 1";

            if(isset($data['keyword']) && $data['keyword'] != ""){
                $keywords = explode(' ', $data['keyword']);
                $searchTermKeywords = array();
                foreach ($keywords as $word) {
                    $word                 = $this->db->escape($word);
                    $searchTermKeywords[] = "(code LIKE '%$word%' OR title LIKE '%$word%' OR description LIKE '%$word%')";
                }
                $query .= ' AND '.implode(' AND ', $searchTermKeywords);
            }

            if(isset($data['status']) && $data['status'] != ""){
                $query .= " AND status='" . (int)$data['status'] . "'";
            }
            
            $stmt = $this->db->query($query);        
            if($stmt->num_rows > 0){
                $total_rows      = $stmt->row['total'];
            }else{
                $total_rows      = 0;
            }

            return $total_rows;
        }

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

        public function generateCodes($discount_type, $discount, $date_start, $date_end, $quantity) {
            for($i = 0; $i < $quantity; $i++) {
                $code = $this->code(6);
                $this->db->query("INSERT INTO {$this->db->prefix}coupon_codes (status, code, discount_type, discount, date_start, date_end) VALUES (1, :code, :discount_type, :discount, :date_start, :date_end)", array(":code"=>$code, ":discount_type"=>$discount_type, ":discount"=>$discount, ":date_start"=>$date_start, ":date_end"=>$date_end));
            }
        }

        public function update($post_data, $id) {
            $code           = $post_data["code"];
            $status         = $post_data["status"];
            $discount_type  = $post_data["discount_type"];
            $discount       = $post_data["discount"];
            $date_start     = $post_data["date_start"];
            $date_end       = $post_data["date_end"];

            $stmt = $this->db->query("UPDATE {$this->db->prefix}coupon_codes SET code=:code, status=:status, discount_type=:discount_type, discount=:discount, date_start=:date_start, date_end=:date_end WHERE id=:id", array(":code"=>$code, ":status"=>$status, ":discount_type"=>$discount_type, ":discount"=>$discount, ":date_start"=>$date_start, ":date_end"=>$date_end, ":id"=>$id));
            if($stmt->error){
                return array("status"=>false, "message"=>"Hata! Bir hata oluştu ve kayıt güncellenemedi.");
            }
            return array("status"=>true, "message"=>"Güncelleme başarılı!");
        }

        function code($length){
            $chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            $res = "";
            for ($i = 0; $i < $length; $i++) {
                $res .= $chars[mt_rand(0, strlen($chars)-1)];
            }
            return $res;
        }
    }