<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Home extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('API_CRUD_model');
        $this->load->library('email');
    }

    public function book_by_category()
    {
        $this->form_validation->set_rules('category_id', 'category id', 'required');
        if ($this->form_validation->run() == false) {
            $errors = $this->form_validation->error_array();
            sort($errors);
            $array = array('status' => 400, 'message' => $errors[0]);
            echo json_encode($array);
            exit;
        } else {
       
            $category_id = $_REQUEST['category_id'];
            $where = 'category_id = "' . $category_id . '" AND book.status = 1';

            $table = 'book';
            $data['page_no'] = isset($_REQUEST['page_no']) ? $_REQUEST['page_no'] : 1;
            // Join data
            $joinData = ['author', 'category'];
            foreach ($joinData as $value) {
                $joinArray[] = ['join' => $value . '.id=' . $table . '.' . $value . '_id', 'table' => $value];
            }
          
            if($where){
                $where = array($where);
            }
            $data['field'] = 'book.*,category.name as category_name,category.image as category_image, author.name as author_name,author.image as author_image';
            $data['table'] = $table;
            $data['joins'] = $joinArray;
            $data['where'] = $where;
            $result = $this->API_CRUD_model->get_join($data);

            if (count($result['data']) > 0) {
                $result_data = $this->get_book_data($result['data']);
                if (sizeof($result_data) > 0) {
                    $response = array('status' => 200, 'message' => 'Record get success', 'result' => $result_data,'total_records'=> $result['total_records'],'total_page'=> $result['total_page']);
                } else {
                    $response = array('status' => 400, 'message' => 'Record not found');
                }
            } else {
                $response = array('status' => 400, 'message' => 'Record not found');
            }
            echo json_encode($response);exit;
        } 
    }

    public function autherlist()
    {
        $data['page_no'] = isset($_REQUEST['page_no']) ? $_REQUEST['page_no'] : 1;
        $data['field'] = 'author.*';
        $data['table'] = 'author';
        $data['joins'] = [];
        $data['where'] = array("role_id=2",'status=1');
        $result = $this->API_CRUD_model->get_join($data);

        $rk = array();
        foreach ($result['data'] as $row) {
            $row->image = base_url() . 'assets/images/author/' . $row->image;
            $rk[] = $row;
        }

        if (sizeof($rk) > 0) {
            $response = array('status' => 200, 'message' => 'Record get successfully', 'result' => $rk,'total_records'=> $result['total_records'],'total_page'=> $result['total_page']);
        } else {
            $response = array('status' => 400, 'message' => 'Record not found');
        }
        echo json_encode($response);
    }

    public function book_by_author()
    {
        $this->form_validation->set_rules('author_id', 'author id', 'required');
        if ($this->form_validation->run() == false) {
            $errors = $this->form_validation->error_array();
            sort($errors);
            $array = array('status' => 400, 'message' => $errors[0]);
            echo json_encode($array);
            exit;
        } else {
       
            $where = 'author_id="' . $_REQUEST['author_id'] . '"';
            $table = 'book';
            $data['page_no'] = isset($_REQUEST['page_no']) ? $_REQUEST['page_no'] : 1;
            $joinData = ['author', 'category'];
            foreach ($joinData as $value) {
                $joinArray[] = ['join' => $value . '.id=' . $table . '.' . $value . '_id', 'table' => $value];
            }
          
            if($where){
                $where = array($where);
            }

            $data['field'] = 'book.*,category.name as category_name,category.image as category_image, author.name as author_name,author.image as author_image';
            $data['table'] = $table;
            $data['joins'] = $joinArray;
            $data['where'] = $where;
            $result = $this->API_CRUD_model->get_join($data);

            if (count($result['data']) > 0) {
                $result_data = $this->get_book_data($result['data']);
                if (sizeof($result_data) > 0) {
                    $response = array('status' => 200, 'message' => 'Record get successfully', 'result' => $result_data,'total_records'=> $result['total_records'],'total_page'=> $result['total_page']);
                } else {
                    $response = array('status' => 400, 'message' => 'Record not found');
                }
                echo json_encode($response);exit;
            } else {
                $response = array('status' => 400, 'message' => 'Record not found');
                echo json_encode($response);exit;
            }
        } 
    }

    public function readcount_by_author()
    {
        $this->form_validation->set_rules('author_id', 'author id', 'required');
        if ($this->form_validation->run() == false) {
            $errors = $this->form_validation->error_array();
            sort($errors);
            $array = array('status' => 400, 'message' => $errors[0]);
            echo json_encode($array);
            exit;
        } else {

            $where = 'author_id="' . $_REQUEST['author_id'] . '"';
            $table = 'book';
            $data['page_no'] = isset($_REQUEST['page_no']) ? $_REQUEST['page_no'] : 1;
            $joinData = ['author', 'category'];
            foreach ($joinData as $value) {
                $joinArray[] = ['join' => $value . '.id=' . $table . '.' . $value . '_id', 'table' => $value];
            }
          
            if($where){
                $where = array($where);
            }

            $data['field'] = 'book.*,sum(readcnt) as readcount, sum(download) as totla_download,category.name as category_name,category.image as category_image, author.name as author_name,author.image as author_image';
            $data['table'] = $table;
            $data['joins'] = $joinArray;
            $data['where'] = $where;
            $result = $this->API_CRUD_model->get_join($data);

            if (sizeof($result['data']) > 0) {
                if (isset($result['data'][0]->id)) {
                    $result_data = $this->get_book_data($result['data']);
                    $response = array('status' => 200, 'message' => 'Record get successfully', 'result' => $result_data);
                } else {
                    $response = array('status' => 400, 'message' => 'Record not found');
                }
            } else {
                $response = array('status' => 400, 'message' => 'Record not found');
            }
            echo json_encode($response);exit;
        } 
    }

    public function booklist()
    {

        $table = 'book';
        $data['page_no'] = isset($_REQUEST['page_no']) ? $_REQUEST['page_no'] : 1;
        // Join data
        $joinData = ['author', 'category'];
        foreach ($joinData as $value) {
            $joinArray[] = ['join' => $value . '.id=' . $table . '.' . $value . '_id', 'table' => $value];
        }

        $where = array($table.'.status="1"');
       
        $data['field'] = 'book.*,category.name as category_name,category.image as category_image, author.name as author_name,author.image as author_image';
        $data['table'] = $table;
        $data['joins'] = $joinArray;
        $data['where'] = $where;
        $result = $this->API_CRUD_model->get_join($data);

        if (count($result['data']) > 0) {
            $result_data = $this->get_book_data($result['data']);
            if (sizeof($result_data) > 0) {
                $response = array('status' => 200, 'message' => 'Record get success', 'result' => $result_data,'total_records'=> $result['total_records'],'total_page'=> $result['total_page']);
            } else {
                $response = array('status' => 400, 'message' => 'Record not found');
            }
        } else {
            $response = array('status' => 400, 'message' => 'Record not found');
        }
        echo json_encode($response);exit;
    }

    public function bookdetails()
    {
        $this->form_validation->set_rules('book_id', 'book id', 'required');
        if ($this->form_validation->run() == false) {
            $errors = $this->form_validation->error_array();
            sort($errors);
            $array = array('status' => 400, 'message' => $errors[0]);
            echo json_encode($array);
            exit;
        } else {

            $book_id = $_REQUEST['book_id'];
            $user_id = isset($_REQUEST['user_id']) ? $_REQUEST['user_id'] : 0;
            $is_buy = 0;
            $transaction_date = '';

            $where = 'book.id="' . $book_id . '"';

            $table = 'book';
            $data['page_no'] = isset($_REQUEST['page_no']) ? $_REQUEST['page_no'] : 1;
            // Join data
            $joinData = ['author', 'category'];
            foreach ($joinData as $value) {
                $joinArray[] = ['join' => $value . '.id=' . $table . '.' . $value . '_id', 'table' => $value];
            }

            if($where){
                $where = array($where);
            }

            $data['field'] = 'book.*,category.name as category_name,category.image as category_image, author.name as author_name,author.image as author_image';
            $data['table'] = $table;
            $data['joins'] = $joinArray;
            $data['where'] = $where;
            $result = $this->API_CRUD_model->get_join($data);

            $where_book_chapter = 'book_id=' . $book_id;
            $book_chapter = $this->API_CRUD_model->get($where_book_chapter, 'book_chapter');
            $book_chapterData = [];

            $is_buy_chapter_for_book = 0;
            if (count($result['data']) > 0) {
                if ($user_id) {
                    $where = 'user_id=' . $user_id . ' AND book_id=' . $book_id.' AND book_chapter_id = 0';
                    $get_tradetail = $this->API_CRUD_model->getById($where, 'transaction');

                    if (isset($get_tradetail->id)) {

                        if($is_buy_chapter_for_book == 0)
                        {
                            $is_buy_chapter_for_book =1;
                            $is_buy = 1;
                            $transaction_date = $get_tradetail->created_at;

                        }
                    }
                }
            }
          
            foreach ($book_chapter as $chapter) {
                $chapter->url = base_url() . 'assets/images/books_chapte/' . $chapter->url;
                $is_buy_chapter = 0;
                $get_tradetail_date = '';

                if($is_buy_chapter_for_book == 1)
                {
                   $chapter->is_buy = 1;

                }else{
                    if ($user_id) {
                        $where = 'user_id=' . $user_id . ' AND book_chapter_id=' . $chapter->id;
                      
                        $get_tradetail = $this->API_CRUD_model->getById($where, 'transaction');

                        if (isset($get_tradetail->id)) {
                            $is_buy_chapter = 1;
                            $get_tradetail_date = $get_tradetail->created_at;
                        }
                    }
                    $chapter->transaction_date = $get_tradetail_date;
                    $chapter->is_buy = $is_buy_chapter;
                }

                $book_chapterData[] = $chapter;
            }

            

            $result_data = $this->get_book_data($result['data']);
            if (count($result_data) > 0) {
                $result_data[0]->is_buy = $is_buy;
                $result_data[0]->transaction_date = $transaction_date;
                $result_data[0]->book_chapter = $book_chapterData;
            }
            if (sizeof($result_data) > 0) {
                $response = array('status' => 200, 'message' => 'Record get success', 'result' => $result_data);
            } else {
                $response = array('status' => 400, 'message' => 'Record not found');
            }
            echo json_encode($response);
        } 
    }

    public function alsolike()
    {
        $result = $this->get_book_join('', 'download', 'DESC');
        if (count($result['data']) > 0) {
            $result_data = $this->get_book_data($result['data']);
            if (sizeof($result_data) > 0) {
                $response = array('status' => 200, 'message' => 'Record get success', 'result' => $result_data,'total_records'=> $result['total_records'],'total_page'=> $result['total_page']);
            } else {
                $response = array('status' => 400, 'message' => 'Record not found');
            }
        } else {
            $response = array('status' => 400, 'message' => 'Record not found');
        }
        echo json_encode($response);exit;
    }

    public function popularbooklist()
    {
        $result = $this->get_book_join('', 'readcnt', 'DESC');
        if (count($result['data']) > 0) {
            $result_data = $this->get_book_data($result['data']);
            if (sizeof($result_data) > 0) {
                $response = array('status' => 200, 'message' => 'Record get success', 'result' => $result_data,'total_records'=> $result['total_records'],'total_page'=> $result['total_page']);
            } else {
                $response = array('status' => 400, 'message' => 'Record not found');
            }
        } else {
            $response = array('status' => 400, 'message' => 'Record not found');
        }
        echo json_encode($response);exit;
    }

    public function free_paid_booklist()
    {
        $is_paid = isset($_REQUEST['is_paid']) ? $_REQUEST['is_paid'] : 0;
        $where = 'is_paid="' . $is_paid . '" ';
        $result = $this->get_book_join($where, 'readcnt', 'DESC');

        if (count($result['data']) > 0) {
            $result_data = $this->get_book_data($result['data']);
            if (sizeof($result_data) > 0) {
                $response = array('status' => 200, 'message' => 'Record get success', 'result' => $result_data,'total_records'=> $result['total_records'],'total_page'=> $result['total_page']);
            } else {
                $response = array('status' => 400, 'message' => 'Record not found');
            }
        } else {
            $response = array('status' => 400, 'message' => 'Record not found');
        }
        echo json_encode($response);exit;
    }

    public function related_item()
    {

        if (isset($_REQUEST['category_id'])) {
            $category_id = $_REQUEST['category_id'];
            $where = 'category_id="' . $category_id . '" ';

            $result = $this->get_book_join($where, 'readcnt', 'DESC');

            if (count($result['data']) > 0) {
                $result_data = $this->get_book_data($result['data']);
                if (sizeof($result_data) > 0) {
                    $response = array('status' => 200, 'message' => 'Record get success', 'result' => $result_data,'total_records'=> $result['total_records'],'total_page'=> $result['total_page']);
                } else {
                    $response = array('status' => 400, 'message' => 'Record not found');
                }
            } else {
                $response = array('status' => 400, 'message' => 'Record not found');
            }
            echo json_encode($response);exit;
        } else {
            $response = array('status' => 400, 'message' => 'Please enter category id');
            echo json_encode($response);exit;
        }
    }

    public function newarriaval()
    {
        $result = $this->get_book_join('', 'id', 'DESC');

        if (count($result['data']) > 0) {

            $result_data = $this->get_book_data($result['data']);
            if (sizeof($result_data) > 0) {
                $response = array('status' => 200, 'message' => 'Record get success', 'result' => $result_data,'total_records'=> $result['total_records'],'total_page'=> $result['total_page']);
            } else {
                $response = array('status' => 400, 'message' => 'Record not found');
            }
        } else {
            $response = array('status' => 400, 'message' => 'Record not found');
        }
        echo json_encode($response);exit;
    }

    public function feature_item()
    {
        $where = 'is_feature="yes" ';
        $result = $this->get_book_join($where, 'id', 'DESC');
        
        if (count($result['data']) > 0) {
            $result_data = $this->get_book_data($result['data']);
            if (sizeof($result_data) > 0) {
                $response = array('status' => 200, 'message' => 'Record get success', 'result' => $result_data,'total_records'=> $result['total_records'],'total_page'=> $result['total_page']);
            } else {
                $response = array('status' => 400, 'message' => 'Record not found');
            }
        } else {
            $response = array('status' => 400, 'message' => 'Record not found');
        }
        echo json_encode($response);exit;
    }

    public function add_download()
    {
        $this->form_validation->set_rules('user_id', 'user id', 'required');
        if ($this->form_validation->run() == false) {
            $errors = $this->form_validation->error_array();
            sort($errors);
            $array = array('status' => 400, 'message' => $errors[0]);
            echo json_encode($array);
            exit;
        } else {

            $user_id = $_REQUEST['user_id'];
            $book_id = isset($_REQUEST['book_id']) ? $_REQUEST['book_id'] : '';
            $magazine_id = isset($_REQUEST['magazine_id']) ? $_REQUEST['magazine_id'] : '';
            
            $add_point = 1;
            if($book_id)
            {           
                $where_down = 'user_id=' . $user_id . ' and book_id="' . $book_id . '"';
                $resultr_down = $this->API_CRUD_model->getById($where_down, 'download');
                if (isset($resultr_down->id)) {
                    $response = array('status' => 201, 'message' => 'Already book download');
                    echo json_encode($response);
                    exit;
                }

                $result = $this->API_CRUD_model->updateByIdWithcount($book_id, 'download', $add_point, 'book');    
            }

            if($magazine_id)
            {             
                $where_down = 'user_id=' . $user_id . ' and magazine_id="' . $magazine_id . '"';
                $resultr_down = $this->API_CRUD_model->getById($where_down, 'download');
                if (isset($resultr_down->id)) {
                    $response = array('status' => 201, 'message' => 'Already magazine download');
                    echo json_encode($response);
                    exit;
                }
                $result = $this->API_CRUD_model->updateByIdWithcount($magazine_id, 'download', $add_point, 'magazine'); 
            }

            $data = array(
                'user_id' => $user_id,
                'book_id' => $book_id,
                'magazine_id' => $magazine_id
            );
           
            $id = $this->API_CRUD_model->insert($data, 'download');
            $response = array('status' => 200, 'message' => 'Download Success');

            echo json_encode($response);
        }
    }

    public function alldownload()
    {
        $this->form_validation->set_rules('user_id', 'user id', 'required');
        if ($this->form_validation->run() == false) {
            $errors = $this->form_validation->error_array();
            sort($errors);
            $array = array('status' => 400, 'message' => $errors[0]);
            echo json_encode($array);
            exit;
        } else {
            if($_POST['type'] == 'book'){
                $user_id = $_REQUEST['user_id'];
                $userId = isset($_POST['user_id']) ? $_POST['user_id'] : '';
                $table = 'download';
                $album_id = isset($_REQUEST['album_id']) ? $_REQUEST['album_id'] : 0;
                $data['page_no'] = isset($_REQUEST['page_no']) ? $_REQUEST['page_no'] : 1;
                $data['order_by'] = 'DESC';
                $data['order_by_field'] = $table.'.id';

                // Join data
                $join_array = array(
                    array('join' => 'book.id='.$table.'.book_id', 'table' => 'book'),
                    array('join' => 'category.id=book.category_id', 'table' => 'category'),
                    array('join' => 'author.id=book.author_id', 'table' => 'author'),
                );

                $where = array($table.'.user_id="'.$_REQUEST['user_id'].'" AND magazine_id=0');
                $data['field'] = 'book.*,category.name as category_name,category.image as category_image, author.name as author_name,author.image as author_image';
                $data['table'] = $table;
                $data['joins'] = $join_array;
                $data['where'] = $where;

                $result = $this->API_CRUD_model->get_join($data);

                if (count($result['data']) > 0) {
                    $result_data = $this->get_book_data($result['data']);
                    if (sizeof($result_data) > 0) {
                        $response = array('status' => 200, 'message' => 'Record get success', 'result' => $result_data,'total_records'=> $result['total_records'],'total_page'=> $result['total_page']);
                    } else {
                        $response = array('status' => 400, 'message' => 'Record not found');
                    }
                    echo json_encode($response);exit;
                } else
                {
                    $response = array('status' => 400, 'message' => 'Record not found');
                    echo json_encode($response);exit;
                }   
            }else
            {
                $user_id = $_REQUEST['user_id'];
                $userId = isset($_POST['user_id']) ? $_POST['user_id'] : '';
                $table = 'download';
                $album_id = isset($_REQUEST['album_id']) ? $_REQUEST['album_id'] : 0;
                $data['page_limit'] = 1000;
                $data['page_no'] = isset($_REQUEST['page_no']) ? $_REQUEST['page_no'] : 1;
                $data['order_by'] = 'DESC';
                $data['order_by_field'] = $table.'.id';

                // Join data
                $join_array = array(
                    array('join' => 'magazine.id='.$table.'.magazine_id', 'table' => 'magazine'),
                    array('join' => 'category.id=magazine.category_id', 'table' => 'category'),
                    array('join' => 'author.id=magazine.author_id', 'table' => 'author'),
                );

                $where = array($table.'.user_id="'.$_REQUEST['user_id'].'" AND book_id=0');
                $data['field'] = 'magazine.*,category.name as category_name,category.image as category_image, author.name as author_name,author.image as author_image';
                $data['table'] = $table;
                $data['joins'] = $join_array;
                $data['where'] = $where;

                $result = $this->API_CRUD_model->get_join($data);
            
                if (count($result['data']) > 0) {
                    $result_data = $this->get_magazine_data($result['data']);
                    if (sizeof($result_data) > 0) {
                        $response = array('status' => 200, 'message' => 'Record get success', 'result' => $result_data,'total_records'=> $result['total_records'],'total_page'=> $result['total_page']);
                    } else {
                        $response = array('status' => 400, 'message' => 'Record not found');
                    }
                    echo json_encode($response);exit;
                }else
                {
                    $response = array('status' => 400, 'message' => 'Record not found');
                    echo json_encode($response);exit;
                }  
            }
        }
    }

    public function all_bookmark()
    {
        $this->form_validation->set_rules('user_id', 'user id', 'required');
        if ($this->form_validation->run() == false) {
            $errors = $this->form_validation->error_array();
            sort($errors);
            $array = array('status' => 400, 'message' => $errors[0]);
            echo json_encode($array);
            exit;
        } else {
        
            $user_id = $_REQUEST['user_id'];
            $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : 'book';

            if($type == 'book'){

                $table = 'bookmark';
                $data['page_no'] = isset($_REQUEST['page_no']) ? $_REQUEST['page_no'] : 1;
                $data['order_by'] = 'DESC';
                $data['order_by_field'] = $table.'.id';

                $join_array = array(
                    array('join' => 'book.id='.$table.'.book_id', 'table' => 'book'),
                    array('join' => 'category.id=book.category_id', 'table' => 'category'),
                    array('join' => 'author.id=book.author_id', 'table' => 'author'),
                );

                $where = array('bookmark.user_id="'.$user_id.'"');
                $data['field'] = 'book.*,category.name as category_name,category.image as category_image, author.name as author_name,author.image as author_image';
                $data['table'] = $table;
                $data['joins'] = $join_array;
                $data['where'] = $where;
                $result = $this->API_CRUD_model->get_join($data);

                $result_data = $this->get_book_data($result['data']);
            }else{

                $table = 'bookmark';
                $data['page_no'] = isset($_REQUEST['page_no']) ? $_REQUEST['page_no'] : 1;
                $data['order_by'] = 'DESC';
                $data['order_by_field'] = $table.'.id';

                $join_array = array(
                    array('join' => 'magazine.id='.$table.'.magazine_id', 'table' => 'magazine'),
                    array('join' => 'category.id=magazine.category_id', 'table' => 'category'),
                    array('join' => 'author.id=magazine.author_id', 'table' => 'author'),
                );

                $where = array('bookmark.user_id="'.$user_id.'"');

                $data['field'] = 'magazine.*,category.name as category_name,category.image as category_image, author.name as author_name,author.image as author_image';
                $data['table'] = $table;
                $data['joins'] = $join_array;
                $data['where'] = $where;
                $result = $this->API_CRUD_model->get_join($data);

                $result_data = $this->get_magazine_data($result['data']);
            } 

            if (sizeof($result_data) > 0) {
                $response = array('status' => 200, 'message' => 'Record get success', 'result' => $result_data,'total_records'=> $result['total_records'],'total_page'=> $result['total_page']);
            } else {
                $response = array('status' => 400, 'message' => 'Record not found');
            }
            echo json_encode($response);exit;
        } 
    }

    public function booksearch()
    {
        $this->form_validation->set_rules('name', 'name', 'required');
        if ($this->form_validation->run() == false) {
            $errors = $this->form_validation->error_array();
            sort($errors);
            $array = array('status' => 400, 'message' => $errors[0]);
            echo json_encode($array);
            exit;
        } else {
            if ($_REQUEST['name']) {
                $whereAuthor = 'name LIKE "%' . $_REQUEST['name'] . '%" ';
                $authorResult = $this->API_CRUD_model->get($whereAuthor, 'author');
                $where_auth = '';
                if (count($authorResult) > 0) {
                    $authorList = [];
                    foreach ($authorResult as $row) {
                        $authorList[] = $row->id;
                    }
                    $imp = implode(',', $authorList);
                    $where_auth = 'OR `author_id` IN (' . $imp . ')';
                }
            }

            if ($_REQUEST['name']) {
                $whereCategory = 'name LIKE "%' . $_REQUEST['name'] . '%" ';
                $categoryResult = $this->API_CRUD_model->get($whereCategory, 'category');
                $where_cat = '';
                if (count($categoryResult) > 0) {
                    $catrList = [];
                    foreach ($categoryResult as $rowcat) {
                        $catrList[] = $rowcat->id;
                    }
                    $catimp = implode(',', $catrList);
                    $where_cat = 'OR `category_id` IN (' . $catimp . ')';
                }
            }

            $where = 'title LIKE "%' . $_REQUEST['name'] . '%" ' . $where_auth . $where_cat.' AND book.status=1';           
 
            $table = 'book';
            $data['page_no'] = isset($_REQUEST['page_no']) ? $_REQUEST['page_no'] : 1;
            // Join data
            $joinData = ['author', 'category'];
            foreach ($joinData as $value) {
                $joinArray[] = ['join' => $value . '.id=' . $table . '.' . $value . '_id', 'table' => $value];
            }
          
            if($where){
                $where = array($where);
            }
            $data['field'] = 'book.*,category.name as category_name,category.image as category_image, author.name as author_name,author.image as author_image';
            $data['table'] = $table;
            $data['joins'] = $joinArray;
            $data['where'] = $where;
            $result = $this->API_CRUD_model->get_join($data);

            if (count($result['data']) > 0) {
                $result_data = $this->get_book_data($result['data']);
                if (sizeof($result_data) > 0) {
                    $response = array('status' => 200, 'message' => 'Record get success', 'result' => $result_data,'total_records'=> $result['total_records'],'total_page'=> $result['total_page']);
                } else {
                    $response = array('status' => 400, 'message' => 'Record not found');
                }
            } else {
                $response = array('status' => 400, 'message' => 'Record not found');
            }
            echo json_encode($response);exit;
        }
    }

    public function purchaselist()
    {
        $this->form_validation->set_rules('user_id', 'user id', 'required');
        $this->form_validation->set_rules('type', 'type', 'required');

        if ($this->form_validation->run() == false) {
            $errors = $this->form_validation->error_array();
            sort($errors);
            $array = array('status' => 400, 'message' => $errors[0]);
            echo json_encode($array);
            exit;
        } else {

            if($_POST['type'] == 'book'){
                $where = 'transaction.user_id=' . $_REQUEST['user_id'];
                $table = 'transaction';
                $data['page_no'] = isset($_REQUEST['page_no']) ? $_REQUEST['page_no'] : 1;
               
                $join_array = array(
                    array('join' => 'book.id='.$table.'.book_id', 'table' => 'book'),
                    array('join' => 'category.id=book.category_id', 'table' => 'category'),
                    array('join' => 'author.id=book.author_id', 'table' => 'author'),
                );
              
                if($where){
                    $where = array($where);
                }
                $data['field'] = 'book.*, transaction.created_at as transaction_date,transaction.amount,author.name as author_name,author.image as author_image';
                $data['table'] = $table;
                $data['joins'] = $join_array;
                $data['where'] = $where;
                $result = $this->API_CRUD_model->get_join($data);

                $total_sum = $this->API_CRUD_model->get_sum($_REQUEST['user_id'],$_POST['type']);

                if (count($result['data']) > 0) {
                    $result_data = $this->get_book_data($result['data']);
                    if (sizeof($result_data) > 0) {
                        $response = array('status' => 200, 'message' => 'Record get success', 'result' => $result_data, 'total_amount' => $total_sum->total_amount,'total_records'=> $result['total_records'],'total_page'=> $result['total_page']);
                    } else {
                        $response = array('status' => 400, 'message' => 'Record not found', 'total_amount' => "0");
                    }
                } else {
                    $response = array('status' => 400, 'message' => 'Record not found', 'total_amount' => "0");
                }
            }else
            {
                $where = 'transaction.user_id=' . $_REQUEST['user_id'];
                $table = 'transaction';
                $data['page_no'] = isset($_REQUEST['page_no']) ? $_REQUEST['page_no'] : 1;
               
                $join_array = array(
                    array('join' => 'magazine.id='.$table.'.magazine_id', 'table' => 'magazine'),
                    array('join' => 'category.id=magazine.category_id', 'table' => 'category'),
                    array('join' => 'author.id=magazine.author_id', 'table' => 'author'),
                );
              
                if($where){
                    $where = array($where);
                }
                $data['field'] = 'magazine.*, transaction.created_at as transaction_date,transaction.amount,author.name as author_name,author.image as author_image';
                $data['table'] = $table;
                $data['joins'] = $join_array;
                $data['where'] = $where;
                $result = $this->API_CRUD_model->get_join($data);

                $total_sum = $this->API_CRUD_model->get_sum($_REQUEST['user_id'],$_POST['type']);

                if (count($result['data']) > 0) {
                    $result_data = $this->get_magazine_data($result['data']);
                    if (sizeof($result_data) > 0) {
                        $response = array('status' => 200, 'message' => 'Record get success', 'result' => $result_data, 'total_amount' => $total_sum->total_amount,'total_records'=> $result['total_records'],'total_page'=> $result['total_page']);
                    } else {
                        $response = array('status' => 400, 'message' => 'Record not found', 'total_amount' => "0");
                    }
                } else {
                    $response = array('status' => 400, 'message' => 'Record not found', 'total_amount' => "0");
                }                 
            }



            echo json_encode($response);exit;
        } 
    }
    
    public function continue_read()
    {
        $this->form_validation->set_rules('user_id', 'user id', 'required');
        if ($this->form_validation->run() == false) {
            $errors = $this->form_validation->error_array();
            sort($errors);
            $array = array('status' => 400, 'message' => $errors[0]);
            echo json_encode($array);
            exit;
        } else {

            $user_id = $_REQUEST['user_id'];
            $where = 'continue_read.user_id='.$user_id;

            $table = 'continue_read';
            $data['page_no'] = isset($_REQUEST['page_no']) ? $_REQUEST['page_no'] : 1;
            // Join data
            $join_array = array(
                array('join' => 'book.id='.$table.'.book_id', 'table' => 'book'),
                array('join' => 'category.id=book.category_id', 'table' => 'category'),
                array('join' => 'author.id=book.author_id', 'table' => 'author'),
            );
          
            if($where){
                $where = array($where);
            }
            $data['field'] = 'book.*,category.name as category_name,category.image as category_image, author.name as author_name,author.image as author_image';
            $data['table'] = $table;
            $data['joins'] = $join_array;
            $data['where'] = $where;
            $result = $this->API_CRUD_model->get_join($data);

            if (count($result['data']) > 0) {
                $result_data = $this->get_book_data($result['data']);
                if (sizeof($result_data) > 0) {
                    $response = array('status' => 200, 'message' => 'Record get success', 'result' => $result_data,'total_records'=> $result['total_records'],'total_page'=> $result['total_page']);
                } else {
                    $response = array('status' => 400, 'message' => 'Record not found');
                }
            } else {
                $response = array('status' => 400, 'message' => 'Record not found');
            }
            echo json_encode($response);exit;
        } 
    }

    public function get_book_join($where='',$field_order='id',$order='DESC')
    {
        $table = 'book';
        $data['page_limit'] = isset($_REQUEST['page_limit']) ? $_REQUEST['page_limit'] :  $this->config->item('page_limit');
        $data['page_no'] = isset($_REQUEST['page_no']) ? $_REQUEST['page_no'] : 1;
        $data['order_by'] = $order;
        $data['group_by'] = '';
        $data['order_by_field'] = $field_order;

        // Join data
        $joinData = ['author', 'category'];
        foreach ($joinData as $value) {
            $joinArray[] = ['join' => $value . '.id=' . $table . '.' . $value . '_id', 'table' => $value];
        }

        $date = date('Y-m-d');

       
        if($where){
            $where = 'book.status=1 AND '.$where;
            $where = array($where);
        }else
        {
             $where = array('book.status=1');
        }

        $data['field'] = 'book.*,category.name as category_name,category.image as category_image, author.name as author_name,author.image as author_image';
        $data['table'] = $table;
        $data['joins'] = $joinArray;
        $data['where'] = $where;
        $result = $this->API_CRUD_model->get_join($data);
        
        return $result;
    }

    public function get_book_data($resultr)
    {
        $rk = array();
        foreach ($resultr as $row) {

            $avg = $this->API_CRUD_model->avg_book_rating($row->id);
            $row->image = base_url() . 'assets/images/book/' . $row->image;
            $row->url = base_url() . 'assets/images/book/' . $row->url;
            $row->sample_url = base_url() . 'assets/images/book/' . $row->sample_url;

            if (isset($row->category_id)) {
                $whereCat = 'id=' . $row->category_id;
                $catg = $this->API_CRUD_model->getById($whereCat, 'category');

                if (isset($catg->id)) {
                    $row->category_name = $catg->name;
                    $row->category_image = $catg->image;
                }
            }

            if (isset($row->category_image)) {
                $row->category_image = base_url() . 'assets/images/category/' . $row->category_image;
            }

            if (isset($row->author_image)) {
                $row->author_image = base_url() . 'assets/images/category/' . $row->author_image;
            }

            $user_id = isset($_POST['user_id']) ? $_POST['user_id'] : '';
            $row->is_download = 0;            
            if ($user_id ) {
                $wheredownload = 'book_id=' .$row->id.' AND user_id='.$user_id;
                $download = $this->API_CRUD_model->getById($wheredownload, 'download');

                if (isset($download->id)) {
                    $row->is_download = 1;
                }
            }

            $row->total_sell = 0;
            $where_transaction = 'book_id=' .$row->id;
            $transaction = $this->API_CRUD_model->get($where_transaction, 'transaction');            
            $row->total_sell = count($transaction);


            $where_book_chapter = 'book_id=' .$row->id;
            $download = $this->API_CRUD_model->get($where_book_chapter, 'book_chapter');
            
            $row->chapter_count = count($download);

            if ($avg->average > 0) {
                $row->avg_rating = number_format($avg->average, 2);
            } else {
                $row->avg_rating = "0";
            }
            $rk[] = $row;
        }
        return $rk;
    }
    
    public function get_magazine_data($result)
    {
        $user_id = isset($_POST['user_id']) ? $_POST['user_id'] : '';
        $rk = array();
        foreach ($result as $row) {

            $avg = $this->API_CRUD_model->avg_magazine_rating($row->id);

            $row->image = base_url() . 'assets/images/magazine/' . $row->image;

            $row->url = base_url() . 'assets/images/magazine/' . $row->url;

            $row->sample_url = base_url() . 'assets/images/magazine/' . $row->sample_url;

            if (isset($row->category_id)) {
                $whereCat = 'id=' . $row->category_id;
                $catg = $this->API_CRUD_model->getById($whereCat, 'category');

                if (isset($catg->id)) {
                    $row->category_name = $catg->name;
                    $row->category_image = $catg->image;
                }
            }

            if (isset($row->category_image)) {
                $row->category_image = base_url() . 'assets/images/category/' . $row->category_image;
            }

            if (isset($row->author_image)) {
                $row->author_image = base_url() . 'assets/images/category/' . $row->author_image;
            }

            $row->is_download = 0;            
            if (isset( $user_id )) {
                $wheredownload = 'magazine_id=' .$row->id.' AND user_id='.$user_id;
                $download = $this->API_CRUD_model->getById($wheredownload, 'download');

                if (isset($download->id)) {
                    $row->is_download = 1;
                }
            }

            $row->total_sell = 0;
            $where_transaction = 'magazine_id=' .$row->id;
            $transaction = $this->API_CRUD_model->get($where_transaction, 'transaction');            
            $row->total_sell = count($transaction);

            if ($avg->average > 0) {
                $row->avg_rating = number_format($avg->average, 2);
            } else {
                $row->avg_rating = "0";
            }
            $rk[] = $row;
        }
        return $rk;
    }

    public function get_transaction() {
        $this->form_validation->set_rules('user_id', 'user id', 'required');
        if ($this->form_validation->run() == false) {
            $errors = $this->form_validation->error_array();
            sort($errors);
            $array = array('status' => 400, 'message' => $errors[0]);
            echo json_encode($array);
            exit;
        } else {

            $table = 'transaction';
            $order = 'DESC';
            $field_order = $table . '.id';
            $data['page_limit'] = isset($_REQUEST['page_limit']) ? $_REQUEST['page_limit'] : $this->config->item('page_limit');
            $data['page_no'] = isset($_REQUEST['page_no']) ? $_REQUEST['page_no'] : 1;
            $data['order_by'] = $order;
            $data['order_by_field'] = $field_order;

            // Join data
            $joinData = $joinArray = [];

            $joinData = array('author');            
            foreach ($joinData as $value) {
                $joinArray[] = ['join' => $value . '.id=' . $table . '.' . $value . '_id', 'table' => $value];
            }

            $where = $table . '.user_id=' . $_REQUEST['user_id'];
            if ($where) {
                $where = array($where);
            }
            $data['field'] = $table . '.*,author.name as author_name,transaction.created_at as transaction_date';
            $data['table'] = $table;
            $data['joins'] = $joinArray;
            $data['where'] = $where;
            $result = $this->API_CRUD_model->get_join($data);
           
            if (count($result['data']) > 0) {
                $BookDetail = [];
                foreach ($result['data'] as $tran) {
                    if ($tran->book_id > 0) {
                        $whereBook = 'id='.$tran->book_id;
                        $books= $this->API_CRUD_model->get($whereBook, 'book');
                        $book = $this->get_book_data($books);
                        if(count($book) > 0){
                            $tran->book_detail = $book[0];
                        }
                        else
                        {
                            $tran->book_detail = (object)array();
                        }
                        // $tran->magazine_detail = (object)array();
                        $BookDetail[] = $tran;
                    }
                    if ($tran->magazine_id > 0) {
                        $whereMagazine = 'id='.$tran->magazine_id;
                        $magazine= $this->API_CRUD_model->get($whereMagazine, 'magazine');
                        $magazines = $this->get_magazine_data($magazine);
                        if(count($magazines) >0){
                            $tran->magazine_detail = $magazines[0];

                            $tran->book_detail = (object)array();
                            $BookDetail[] = $tran;
                        }
                       
                    }                    
                }
              
                if (sizeof($BookDetail) > 0) {
                    $response = array('status' => 200, 'message' => 'Record get success', 'result' => $BookDetail, 'total_records' => $result['total_records'], 'total_page' => $result['total_page']);
                } else {
                    $response = array('status' => 400, 'message' => 'Record not found');
                }
            } else {
                $response = array('status' => 400, 'message' => 'Record not found');
            }
            echo json_encode($response);
            exit;
        }
    }

    public function getPaymentToken(){

        // include '/home/milostar/domains/milostar.live/public_html/nowka/application/controllers/api/PaytmChecksum.php';
        require_once("PaytmChecksum.php");

        $PaytmChecksum = new PaytmChecksum;

        $payment_option_where = 'name="PayTm"';
        $payment_option = $this->API_CRUD_model->getById($payment_option_where, 'payment_option');
         
        $MERCHANTID = '';
        $MERCHANTKEY = '';
        if(isset($payment_option->id))
        {
            if($payment_option->is_live == 1)
            {
                $MERCHANTID = $payment_option->live_key_1;
                $MERCHANTKEY = $payment_option->live_key_2;
            }else
            {
                $MERCHANTID = $payment_option->test_key_1;
                $MERCHANTKEY = $payment_option->test_key_2;
            }
        }

        /* initialize an array */
        $paytmParams = array();

        $order_id = isset($_REQUEST['order_id']) ? $_REQUEST['order_id'] : 1;
        // $MID = isset($_REQUEST['MID']) ? $_REQUEST['MID'] : 'fazUIY24322420334453';

        /* add parameters in Array */
        $paytmParams["MID"] = $MERCHANTID;
        $paytmParams["ORDER_ID "] = $order_id;
        $paytmParams["CUST_ID"] = $_REQUEST['CUST_ID'];
        $paytmParams["CHANNEL_ID"] = $_REQUEST['CHANNEL_ID'];
        $paytmParams["TXN_AMOUNT"] = $_REQUEST['TXN_AMOUNT'];
        $paytmParams["WEBSITE"] = $_REQUEST['WEBSITE'];
        $paytmParams["CALLBACK_URL"] = $_REQUEST['CALLBACK_URL'];
        $paytmParams["INDUSTRY_TYPE_ID"] = $_REQUEST['INDUSTRY_TYPE_ID'];
        
        $paytmChecksum = $PaytmChecksum::generateSignature($paytmParams, $MERCHANTKEY);
        $verifySignature = PaytmChecksum::verifySignature($paytmParams, $MERCHANTKEY, $paytmChecksum);

        $result['paytmChecksum'] = $paytmChecksum;
        $result['verifySignature'] = $verifySignature;
        $response=array('status'=>200,'message'=>'Paytm check sum successfully', 'result'=>$result);    
        echo json_encode($response);
        
    }


    public function getCashfreeToken(){

        $order_id = isset($_REQUEST['orderId']) ? $_REQUEST['orderId'] : 1;
        $orderAmount = isset($_REQUEST['orderAmount']) ? $_REQUEST['orderAmount'] : 1;
        $orderCurrency = isset($_REQUEST['orderCurrency']) ? $_REQUEST['orderCurrency'] : "INR";
        $MID = isset($_REQUEST['MID']) ? $_REQUEST['MID'] : 'XJRkiY27598899103673'; 
        // A sample PHP Script to POST data using cURL
        $data = array(
          'orderId' => $order_id,
          'orderAmount' => $orderAmount,
          'orderCurrency' => $orderCurrency,
        );

        $post_data = json_encode($data);


        $request_headers = array(
            "Content-Type:application/json",
            "x-client-id:394872c69b02bdc6a2e341d2b78493",
            "x-client-secret:dbeb6c324b41b596190c5825b3c2df42429c7d4c"
        );

        // Prepare new cURL resource
        $crl = curl_init('https://test.cashfree.com/api/v2/cftoken/order');
        curl_setopt($crl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($crl, CURLOPT_HTTPHEADER, $request_headers);
        curl_setopt($crl, CURLOPT_POST, true);
        curl_setopt($crl, CURLOPT_POSTFIELDS, $post_data);
    
        // Submit the POST request
        $result = curl_exec($crl);
    
        // Close cURL session handle
        curl_close($crl);

        $resultData = json_decode($result);
        $resultData->orderId = $order_id;
        echo json_encode($resultData);
    }

}