<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Class : Login_model (Login Model)
 * Login model class to get to authenticate user credentials 
 * @author : Kishor Mali
 * @version : 1.1
 * @since : 15 November 2016
 */
class CRUD_model extends CI_Model {

    public function __construct() {
        $this->load->database();
    }

    public function getAdminAuthorEarning() {
        $this->db->select("sum(author_commission_amount) as total_commission, sum(amount) as total_earning");
        $this->db->from("transaction");
        $this->db->where('settle', '0');
        $q = $this->db->get();
        return $q->row();
    }

    public function getAuthorEarning($id) {
        $this->db->select("sum(author_commission_amount) as total_commission, sum(amount) as total_earning");
        $this->db->from("transaction");
        $this->db->where('author_id', $id);
        $this->db->where('settle', '0');
        $q = $this->db->get();
        return $q->row();
    }

    public function update_currency() {
        $isInsert = isInsert();

        if ($isInsert == 1) {
            return true;
        }

        $insert['status'] = 0;
        $this->db->update('currency', $insert);
    }

    public function getSalesReport($id, $start_date, $end_date) {
        $this->db->select("transaction.*,user.fullname,book.title,author.name");
        $this->db->from("transaction");
        $this->db->join('user', "transaction.user_id=user.id");
        $this->db->join('book', "transaction.book_id=book.id");
        $this->db->join('author', "transaction.author_id=author.id");
        if ($id) {
            $this->db->where('transaction.author_id', $id);
        }
        $this->db->where('settle', '0');
        $this->db->where('transaction.created_at >=', $start_date);
        $this->db->where('transaction.created_at <=', $end_date);
        $q = $this->db->get();
        return $q->result();
    }

    public function getSalesMagazineReport($id, $start_date, $end_date) {
        $this->db->select("transaction.*,user.fullname,magazine.title,author.name");
        $this->db->from("transaction");
        $this->db->join('user', "transaction.user_id=user.id");
        $this->db->join('magazine', "transaction.magazine_id=magazine.id");
        $this->db->join('author', "transaction.author_id=author.id");
        if ($id) {
            $this->db->where('transaction.author_id', $id);
        }
        $this->db->where('settle', '0');
        $this->db->where('transaction.created_at >=', $start_date);
        $this->db->where('transaction.created_at <=', $end_date);
        $q = $this->db->get();
        return $q->result();
    }

    public function getCountData($where,$tableName, $groupBy, $count) {
        if($count){
            $this->db->select($count);
        }else{
            $this->db->select($tableName.'.*');
        }
        
        $this->db->from($tableName);
        
        if ($where) {
            $this->db->where($where);
        }
        if ($groupBy) {
            $this->db->group_by($groupBy);
        }
        $q = $this->db->get();
        $row = $q ->row();
        return $row;
    }

    
    public function getCountDataOrderBy($where,$tableName, $groupBy, $count,$order_by,$order_by_field,$limit) {
        
        $this->db->select($count);
        
        $this->db->from($tableName);  

        $this->db->join('author', 'author.id = transaction.author_id');
  
        if ($where) {
            $this->db->where($where);
        }
        
        if ($groupBy) {
            $this->db->group_by($groupBy);
        }

        if ($order_by_field) {
            $this->db->order_by($order_by_field, $order_by);
        }

        if ($order_by_field) {
            $this->db->limit($limit);
        }

        $q = $this->db->get();
        $row = $q ->result();
        return $row;
    }

    public function getSalesReportMonth($id, $start_date, $end_date) {
        $this->db->select("transaction.*,author.name,sum(author_commission_amount) as total_admin_commission_amount, sum(amount) as total_amount");
        $this->db->from("transaction");
        $this->db->join('author', "transaction.author_id=author.id");
        if ($id) {
            $this->db->where('transaction.author_id', $id);
        }
        $this->db->group_by("transaction.author_id");
        $this->db->where('settle', '0');
        $this->db->where('transaction.created_at >=', $start_date);
        $this->db->where('transaction.created_at <=', $end_date);
        $q = $this->db->get();
        return $q->result();
    }

    public function view_website($where) {
        $this->db->set('views', 'views+1', FALSE);
        $this->db->where($where);
        $this->db->update('website_analysis');
    }

    public function get_book_id($id) {
        $this->db->select("*");
        $this->db->from("book");
        $this->db->where_in('id', $id);
        $q = $this->db->get();
        return $q->result();
    }

    // Get count 
    public function getCount($where, $tablename) {
        $this->db->select('*');
        $this->db->from($tablename);
        if (!empty($where)) {
            $this->db->where($where);
        }
        $query = $this->db->get();
        $row = $query->result();
        return $row;
    }

    public function updateByIdWithcount($id, $field_name, $value, $tablename) {
        $this->db->set($field_name, $field_name . '+' . $value, FALSE);
        $this->db->where('id', $id);
        $this->db->update($tablename);
        return $id;
    }

    public function get($where, $tablename, $field_name = null, $order_by = 'desc') {
        $this->db->select('*');
        $this->db->from($tablename);
        if (!empty($where)) {
            $this->db->where($where);
        }
        if ($field_name) {
            $this->db->order_by($field_name, $order_by);
        }
        $query = $this->db->get();
        $row = $query->result();
        return $row;
    }

    public function getById($where, $tablename) {
        $this->db->select('*');
        $this->db->from($tablename);
        if (!empty($where)) {
            $this->db->where($where);
        }
        $query = $this->db->get();
        $row = $query->row();
        return $row;
    }

    public function get_join_allrecord($table1, $table2, $joinid, $field, $where = Null, $order_by = Null) {
        $this->db->select($field);
        $this->db->from($table1);
        $this->db->join($table2, $joinid);

        if($order_by){
            $this->db->order_by($table1.'.id', "desc");
        }
        $query = $this->db->get();
        $row = $query->result();
        return $row;
    }

    public function get_join($data)
    {

      $where = isset($data['where']) ? $data['where'] : '';
      $whereIn = isset($data['where_in']) ? $data['where_in'] : '';
      $group_by = isset($data['group_by']) ? $data['group_by'] : '';
      $order_by_field = isset($data['order_by_field']) ? $data['order_by_field'] : '';
      $order_by = isset($data['order_by']) ? $data['order_by'] : '';
      $page_no = isset($data['page_no']) ? $data['page_no'] : '';
      $page_limit = isset($data['page_limit']) ? $data['page_limit'] : '';
      
      $this->db->select($data['field']);
      $this->db->from($data['table']);

      if(isset($data['joins'])){
        foreach ($data['joins'] as $joins) {
            $this->db->join($joins['table'], $joins['join']);
        }
      }

      if($where){
          foreach ($where as $value) {
              $this->db->where($value);
          }
      }

      if($whereIn){

          foreach ($whereIn as $value) {

              $this->db->where("FIND_IN_SET(".$value['value'].",`".$value['key']."`) <>",'0');
          }
      }

      if ($order_by_field) {
          $this->db->order_by($order_by_field, $order_by);
      }

      if ($group_by) {
          $this->db->group_by($group_by);
      }

      if ($page_no) {
          $offset = ($page_limit * $page_no) - $page_limit;
          $this->db->limit($page_limit, $offset);
      }
      
      $query = $this->db->get();
      // p($this->db->last_query());
      $row = $query->result();
      return $row;
  }

    public function get_two_join_allrecord($table1, $table2, $table3, $joinid1, $joinid2, $field) {
        $this->db->select($field);
        $this->db->from($table1);
        $this->db->join($table2, $joinid1);
        $this->db->join($table3, $joinid2);
        $query = $this->db->get();
        $row = $query->result();
        return $row;
    }

      public function updateById($id,$field_name,$data,$tablename){
       $isInsert = isInsert();
        if($isInsert  == 1)
        {
            return true;
        }

        $this->db->where($field_name, $id);
        $this->db->update($tablename, $data);
        return $id; 
    } 
    public function getLastRecord($where, $tablename) {
        $this->db->select('*');
        $this->db->from($tablename);
        $this->db->where($where);
        $this->db->limit(1);
        $this->db->order_by('id', "desc");
        $query = $this->db->get();
        $row = $query->row();
        return $row;
    }

    public function insert($data, $tablename) {

        $isInsert = isInsert();

        if ($isInsert == 1) {
            return true;
        }

        $insert = [];
        foreach ($data as $key => $value) {
            $insert[$key] = $this->db->escape_str($value);
        }

        $query = $this->db->insert($tablename, $data);
        return $this->db->insert_id();
    }

    public function update($id, $field_name, $data, $tablename) {
        $isInsert = isInsert();
        if ($isInsert == 1) {
            return true;
        }

        $insert = [];
        foreach ($data as $key => $value) {
            $insert[$key] = $this->db->escape_str($value);
        }

        $this->db->where($field_name, $id);
        $this->db->update($tablename, $insert);
        return $id;
    }

    public function delete($where, $tablename) {
        $isInsert = isInsert();
        if ($isInsert == 1) {
            return true;
        }
        $this->db->where($where);
        $this->db->delete($tablename);
        return true;
    }

    public function delete_all($id, $field_name, $tablename) {
        $isInsert = isInsert();
        if ($isInsert == 1) {
            return true;
        }

        if($tablename == 'book'){
            $where = 'id='.$id;
            $book = $this->getById($where,$tablename);

            $bookPath = FCPATH . 'assets/images/book/'.$book->image;
            unlink($bookPath);
            
            $sample_urlPath = FCPATH . 'assets/images/book/'.$book->sample_url;
            unlink($sample_urlPath);

            $urlPath = FCPATH . 'assets/images/book/'.$book->url;
            unlink($urlPath);          
        }


        if($tablename == 'magazine'){
            $where = 'id='.$id;
            $magazine = $this->getById($where,$tablename);

            $bookPath = FCPATH . 'assets/images/magazine/'.$magazine->image;
            unlink($bookPath);
            
            $sample_urlPath = FCPATH . 'assets/images/magazine/'.$magazine->sample_url;
            unlink($sample_urlPath);

            $urlPath = FCPATH . 'assets/images/magazine/'.$magazine->url;
            unlink($urlPath);          
        }

        if($tablename == 'book_chapter'){
            $where = 'id='.$id;
            $book = $this->getById($where,$tablename);

            $urlPath = FCPATH . 'assets/images/books_chapte/'.$book->url;
            unlink($urlPath);          
        }
        
        if($tablename == 'ads_banner'){

            $where = 'id='.$id;
            $ads_banne = $this->getById($where,$tablename);
            $urlPath = FCPATH . 'assets/images/banner/'.$ads_banne->image;
            unlink($urlPath);          
        }


        if($tablename == 'category'){
            $where = 'id='.$id;
            $category = $this->getById($where,$tablename);
            $urlPath = FCPATH . 'assets/images/category/'.$category->image;
            unlink($urlPath);          
        }



        $this->db->where($field_name, $id);
        $this->db->delete($tablename);
        return true;
    }

    public function imageupload($imageName, $imgname, $uploadpath, $widths = 2500, $heights = 2500) {

        if (!file_exists($uploadpath)) {
            mkdir($uploadpath, 0777, true);
        }

        if (empty($imageName['name'])) {
            $res = array('status' => '400', 'message' => 'Please Upload Image first.');
            echo json_encode($res);
            exit;
        }
        if (!empty($imageName['name']) && ($imageName['error'] == 1 || $imageName['size'] > 52150000)) {
            $res = array('status' => '202', 'message' => 'Max 50MB file is allowed for image.');
            echo json_encode($res);
            exit;
        } else {
            list($width, $height) = getimagesize($imageName['tmp_name']);
            if ($width > $widths || $height > $heights) {
                $res = array('status' => '201', 'message' => 'Image height and width must be less than height .' . $heights . ' and width ' . $widths);
                echo json_encode($res);
                exit;
            } else {

                $catImg = $imageName['name'];
                $ext = pathinfo($catImg);
                $catImages = str_replace(array(' ', '.', '-', '`'), '_', $ext['filename']);

                $imgname_s = $imgname;
                if ($imgname == 'url') {
                    $imgname_s = 'book';
                }
                $category_image = $imgname_s . '_' . time() . '.' . $ext['extension'];
                $config = array(
                    'allowed_types' => '*',
                    'upload_path' => $uploadpath,
                    'file_name' => $category_image
                );
                $this->load->library('upload');
                $this->upload->initialize($config);
                $this->upload->do_upload($imgname);
                return $category_image;
            }
        }
    }

    public function videoupload($imageName, $imgname, $uploadpath) {

        if (empty($imageName['name'])) {
            $res = array('status' => '400', 'message' => 'Please Upload Image first.');
            echo json_encode($res);
            exit;
        }

        $catImg = $imageName['name'];
        $ext = pathinfo($catImg);
        $catImages = str_replace(array(' ', '.', '-', '`'), '_', $ext['filename']);
        $category_image = time() . '.' . $ext['extension'];
        $config = array(
            'allowed_types' => '*',
            'upload_path' => $uploadpath,
            'file_name' => $category_image
        );
        $this->load->library('upload');
        $this->upload->initialize($config);
        $this->upload->do_upload($imgname);
        return $category_image;
    }

    
    public function make_query($table, $select_column, $order_column, $searcharray = null, $where = null) {
        $this->db->select($select_column);
        $this->db->from($table);

        $text = 'id >0 ';

        if (isset($_POST["search"]["value"]) && $_POST["search"]["value"] != '') {
            if ($searcharray) {
                $text .= ' AND (';
                foreach ($searcharray as $key => $value) {
                    if (count($searcharray) == $key + 1) {
                        $text .= $value . ' LIKE "%' . $_POST["search"]["value"] . '%"';
                    } else {
                        $text .= $value . ' LIKE "%' . $_POST["search"]["value"] . '%" OR ';
                    }
                }
                $text .= ')';
            }
        }
        $this->db->where($text);

        if ($where) {
            $this->db->where($where);
        }

        if (isset($_POST["order"])) {
            $this->db->order_by($order_column[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
        } else {
            $this->db->order_by('id', 'DESC');
        }
    }

    function make_datatables($table, $select_column, $order_column, $search = null, $where = null) {
        $this->make_query($table, $select_column, $order_column, $search, $where);
        if ($_POST["length"] != -1) {
            $this->db->limit($_POST['length'], $_POST['start']);
        }
        $query = $this->db->get();
        return $query->result();
    }

    function get_filtered_data($table, $select_column, $order_column, $search = null, $where = null) {
        $this->make_query($table, $select_column, $order_column, $search, $where);
        $query = $this->db->get();
        if ($where) {
            $this->db->where($where);
        }
        return $query->num_rows();
    }

    function get_all_data($table, $where = null) {
        $this->db->select("*");
        $this->db->from($table);
        if ($where) {
            $this->db->where($where);
        }
        return $this->db->count_all_results();
    }

   public function get_category_list($name=Null) {

        $this->db->select('*');
        $this->db->from('category');
        $this->db->order_by("id", "desc");
        if($name)
        {
            $this->db->like('name', $name);
        }
        
        $query = $this->db->get();
        return $query->result_array();
    }

    public function categoryList($limit, $start,$name=Null) {
        $offset = ($limit * $start) - $limit;
        $this->db->limit($limit, $offset);
        $this->db->select('*');
        $this->db->from('category');
        
        if($name)
        {
            $this->db->like('name', $name);
        }
        
        $this->db->order_by("id", "desc");
        $query = $this->db->get();
        return $query->result_array();
    }

}

?>