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

class Book extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        frontendcheck();
    }

    public function index()
    {
        $this->load->view("admin/book/list");
    }

    public function add()
    {
        $data['booklist'] = $this->CRUD_model->get('', 'book');
        $where = 'role_id =2';
        $data['authorlist'] = $this->CRUD_model->get($where, 'author');
        $data['categorylist'] = $this->CRUD_model->get('', 'category');
        $this->load->view("admin/book/add", $data);
    }

    public function save()
    {
        $this->form_validation->set_rules('title', 'Book Name', 'required');
        $this->form_validation->set_rules('is_paid', 'Book Cost ', 'required');
        $this->form_validation->set_rules('category_id', 'Category', 'required');
        $this->form_validation->set_rules('author_id', 'Author', 'required');
        // $this->form_validation->set_rules('mp3_file_name', 'full book', 'required');

        if ($this->form_validation->run() == false) {
            $errors = $this->form_validation->error_array();
            sort($errors);
            $array = array('status' => 400, 'message' => $errors);
            echo json_encode($array);exit;
        } else {
            // $data = $_POST;
            $data['image'] = '';
            if (isset($_FILES['image']['name']) && $_FILES['image']['name'] != '') {
                $data['image'] = $this->CRUD_model->imageupload($_FILES['image'], 'image', FCPATH . 'assets/images/book');
            } else {
                $array = array('status' => 400, 'message' => array('Please Select Book Cover Poster'));
                echo json_encode($array);exit;
            }

            if (isset($_FILES['sample_url']) && !empty($_FILES['sample_url']['name'])) {
                $data['sample_url'] = $this->CRUD_model->imageupload($_FILES['sample_url'], 'sample_url', FCPATH . 'assets/images/book');
            } else {
                $array = array('status' => 400, 'message' => array('Please select sample book image'));
                echo json_encode($array);exit;
            }

            $data['url'] = isset($_POST['mp3_file_name']) ? $_POST['mp3_file_name'] : '';

            $data['title'] = $_POST['title'];
            $data['category_id'] = $_POST['category_id'];
            $data['is_paid'] = $_POST['is_paid'];
            $data['price'] = isset($_POST['price']) ? $_POST['price'] : '0';
            $data['author_id'] = $_POST['author_id'];
            $data['description'] = $_POST['description'];
            $data['status'] = "1";

            $id = $this->CRUD_model->insert($data, 'book');

            if ($id) {
                $res = array('status' => '200', 'message' => 'Book added successfully.', 'id' => $id);
                echo json_encode($res);exit;
            } else {
                $res = array('status' => '400', 'message' => 'fail');
                echo json_encode($res);exit;
            }
        }
    }

    public function edit()
    {
        $id = $_GET['id'];
        $data['categorylist'] = $this->CRUD_model->get('', 'category');

        $where = 'id="' . $id . '"';
        $data['booklist'] = $this->CRUD_model->getById($where, 'book');

        $where_authorlist = 'role_id =2';
        $data['authorlist'] = $this->CRUD_model->get($where_authorlist, 'author');

        $this->load->view("admin/book/edit", $data);
    }

    public function update()
    {
        $this->form_validation->set_rules('title', 'Book Name', 'required');
        $this->form_validation->set_rules('is_paid', 'Book Cost ', 'required');
        $this->form_validation->set_rules('category_id', 'Category', 'required');
        $this->form_validation->set_rules('author_id', 'Author', 'required');

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

            if (isset($_FILES['image']) && !empty($_FILES['image']['name'])) {
                $data['image'] = $this->CRUD_model->imageupload($_FILES['image'], 'image', FCPATH . 'assets/images/book');
            } else {
                $data['image'] = $_POST['inputbookcover'];
            }

            if (isset($_FILES['sample_url']) && !empty($_FILES['sample_url']['name'])) {
                $data['sample_url'] = $this->CRUD_model->imageupload($_FILES['sample_url'], 'sample_url', FCPATH . 'assets/images/book');

            } else {
                $data['sample_url'] = $_POST['inputsamplebook'];
            }

            if (isset($_POST['mp3_file_name']) && !empty($_POST['mp3_file_name'])) {
                $data['url'] = $_POST['mp3_file_name'];
            } else {
                $data['url'] = $_POST['mp3_file_name_edit'];
            }

            $data['title'] = $_POST['title'];
            $data['category_id'] = $_POST['category_id'];
            $data['is_paid'] = $_POST['is_paid'];
            $data['price'] = isset($_POST['price']) ? $_POST['price'] : '0';
            $data['author_id'] = $_POST['author_id'];
            $data['description'] = $_POST['description'];

            $id = $this->CRUD_model->update($_POST['id'], 'id', $data, 'book');

            if ($id) {
                $res = array('status' => '200', 'message' => 'Book added successfully.', 'id' => $id);
                echo json_encode($res);exit;
            } else {
                $res = array('status' => '400', 'message' => 'Please try again');
                echo json_encode($res);exit;
            }
        }
    }

    public function fetch_data()
    {

        $table = "book";
        $select_column = array("id", "author_id", "title", "readcnt", "image", "price", "download");
        $order_column = array(null, "title", "readcnt", null, null);
        $search = array('title', 'readcnt', 'download');

        $where = '';
        if ($_SESSION['role_id'] == 2) {
            $author_id = $_SESSION['id'];
            $where = 'author_id=' . $author_id;
        }

        $fetch_data = $this->CRUD_model->make_datatables($table, $select_column, $order_column, $search, $where);
        $data = array();
        foreach ($fetch_data as $key => $row) {
            $whereauthor = 'id=' . $row->author_id;
            $author = $this->CRUD_model->getById($whereauthor, 'author');
            $author_name = '';
            $author_name = isset($author->name) ? $author->name : '';

            $wherebook = 'book_id='.$row->id;
            $book_count = $this->CRUD_model->get($wherebook, 'transaction');
            
            $total_sales = count($book_count);


            $sub_array = array();
            $sub_array[] = '<img src="' . get_image_path($row->image, "book") . '" width="50" height="50" />';
            $sub_array[] = $row->title;
            $sub_array[] = $author_name;
            $sub_array[] = $row->price;
            $sub_array[] = $total_sales;

            $sub_array[] = '<a class="btn btn-xs btn-dark p-1" href="' . base_url() . 'admin/book/chapter_list/' . $row->id . '"> <i class="fa fa-book p-1"></i> </a> <a href="' . base_url() . 'admin/book/edit?id=' . $row->id . '" class="btn btn-xs btn-primary p-1" ><i class="fa fa-edit p-1"></i></a>  <a href="javaScript:void(0)" class="btn btn-xs btn-danger p-1" onclick="delete_record(' . $row->id . ',\'book\')"><i class="fa fa-trash p-1"></i></a>';
            $data[] = $sub_array;
        }


        $rrr  = $this->CRUD_model->get_filtered_data($table, $select_column, $order_column, $search, $where);
      
        $output = array(
            "draw" => intval($_POST["draw"]),
            "recordsTotal" => $this->CRUD_model->get_all_data($table),
            "recordsFiltered" => $this->CRUD_model->get_filtered_data($table, $select_column, $order_column, $search, $where),
            "data" => $data,
        );


        echo json_encode($output);
    }

    public function chapter_list($book_id = '')
    {
        if ($book_id) {

            $where = 'book_id="' . $book_id . '"';
            $data['book_id'] = $book_id;
            $data['book_chapter'] = $this->CRUD_model->get($where, 'book_chapter');

            $this->load->view("admin/book/list_chapter", $data);
        } else {
            redirect(base_url() . 'admin/book/index');
        }
    }

    public function saveBookChapter()
    {
        $this->form_validation->set_rules('title', 'Chapter Name', 'required');
        if ($this->form_validation->run() == false) {
            $errors = $this->form_validation->error_array();
            sort($errors);
            $array = array('status' => 400, 'message' => $errors);
            echo json_encode($array);exit;
        } else {
            $data = $_POST;

            if (isset($_FILES['url']) && !empty($_FILES['url']['name'])) {
                $data['url'] = $this->CRUD_model->imageupload($_FILES['url'], 'url', FCPATH . 'assets/images/books_chapte');
            } else {
                $array = array('status' => 400, 'message' => array('Please Select Chapter.'));
                echo json_encode($array);exit;
            }

            $id = $this->CRUD_model->insert($data, 'book_chapter');

            if ($id) {
                $res = array('status' => '200', 'message' => ' Chapter added successfully.', 'id' => $data['book_id']);
                echo json_encode($res);exit;
            } else {
                $res = array('status' => '400', 'message' => 'fail');
                echo json_encode($res);exit;
            }
        }
    }
}