<?php

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

class Magazine extends CI_Controller {

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

    public function magazinedetails() {
        $this->form_validation->set_rules('magazine_id', 'magazine_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 {

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

            $where = 'magazine.id="' . $magazine_id . '"';

            $table = 'magazine';
            $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'] = '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'] = $joinArray;
            $data['where'] = $where;
            $result = $this->API_CRUD_model->get_join($data);

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

                    if (isset($get_tradetail->id)) {
                        $is_buy = 1;
                        $transaction_date = $get_tradetail->created_at;
                    }
                }
            }
            $result_data = $this->get_magazine_data($result['data']);
            if (count($result_data) > 0) {
                $result_data[0]->is_buy = $is_buy;
                $result_data[0]->transaction_date = $transaction_date;
            }
            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);
        }
    }

    public function get_magazine_join($where = '', $field_order = 'id', $order = 'DESC') {
        $table = 'magazine';
        $data['page_no'] = isset($_REQUEST['page_no']) ? $_REQUEST['page_no'] : 1;
        $data['order_by'] = $order;
        $data['order_by_field'] = $field_order;
        $joinData = ['author', 'category'];
        foreach ($joinData as $value) {
            $joinArray[] = ['join' => $value . '.id=' . $table . '.' . $value . '_id', 'table' => $value];
        }

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

       
        
        $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'] = $joinArray;
        $data['where'] = $where;
        $result = $this->API_CRUD_model->get_join($data);
        return $result;
    }

    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/book/' . $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 popularMagazine() {
        $result = $this->get_magazine_join('', 'readcnt', 'DESC');
        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');
            }
        } else {
            $response = array('status' => 400, 'message' => 'Record not found');
        }
        echo json_encode($response);
        exit;
    }

    public function topMagazine() {


        $result = $this->get_magazine_join('', 'id', 'DESC');

        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');
            }
        } else {
            $response = array('status' => 400, 'message' => 'Record not found');
        }
        echo json_encode($response);
        exit;
    }

    public function topDownloadMagazine() {
        $result = $this->get_magazine_join('', 'download', 'DESC');
        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');
            }
        } else {
            $response = array('status' => 400, 'message' => 'Record not found');
        }
        echo json_encode($response);
        exit;
    }

    public function magazine_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'];

            $table = 'magazine';
            $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('magazine.status=1 AND magazine.category_id=' . $category_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'] = $joinArray;
            $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');
                }
            } else {
                $response = array('status' => 400, 'message' => 'Record not found');
            }
            echo json_encode($response);
            exit;
        }
    }

    public function magazine_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 = 'magazine';
            $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'] = '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'] = $joinArray;
            $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 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 add_magazine_rating() {
        $this->form_validation->set_rules('magazine_id', 'magazine_id', 'required');
        $this->form_validation->set_rules('user_id', 'user_id', 'required');
        $this->form_validation->set_rules('rating', 'rating', '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 {

            $magazine_id = $_REQUEST['magazine_id'];
            $user_id = $_REQUEST['user_id'];
            $ratingData = $_REQUEST['rating'];
            $where = 'magazine_id="' . $magazine_id . '" and user_id="' . $user_id . '"';
            $rating = $this->API_CRUD_model->getById($where, 'rating_magazine');

            $data = array(
                'magazine_id' => $magazine_id,
                'user_id' => $user_id,
                'rating' => $ratingData);

            if (isset($rating->id)) {
                $where = 'rating_id="' . $rating->id . '"';
                $this->API_CRUD_model->update($rating->id, 'id', $data, 'rating_magazine');
            } else {
                $this->API_CRUD_model->insert($data, 'rating_magazine');
            }

            $response = array('status' => 200, 'message' => 'Success');
            echo json_encode($response);
        }
    }

    public function magazinesearch() {
        $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 magazine.status=1';

            $table = 'magazine';
            $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'] = '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'] = $joinArray;
            $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');
                }
            } else {
                $response = array('status' => 400, 'message' => 'Record not found');
            }
            echo json_encode($response);
            exit;
        }
    }

}
