<?php

class Product extends MY_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('Category_model');
        $this->load->model('Product_model');
        $this->load->helper('slug_helper');
        $this->load->helper('product_helper');
        $this->load->library('upload');
    }

    public function index($page = 1) {
        //load model
        $this->load->model("Basic_model");

        $data['title'] = 'Product';
        $data['content'] = 'admin/product/index';

        $products = $this->Product_model->getProducts(8, ($page - 1) * 8);
        // $this->output->enable_profiler(TRUE);

        $total_products = $this->Product_model->get_total();
        $data["products"] = $products;
        //pagination
        $this->load->library('pagination');
        $config['base_url'] = base_url('admin/product/index');
        $config['total_rows'] = $total_products;
        $config['per_page'] = 8;
        // $config['uri_segment'] = 2;
        $config['use_page_numbers'] = TRUE;
        $config["cur_page"] = $page;

        $config['full_tag_open'] = "<ul class='pagination'>";
        $config['full_tag_close'] = "</ul>";
        $config['num_tag_open'] = '<li>';
        $config['num_tag_close'] = '</li>';
        $config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='javascript:void(0)'>";
        $config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
        $config['next_tag_open'] = "<li>";
        $config['next_tagl_close'] = "</li>";
        $config['prev_tag_open'] = "<li>";
        $config['prev_tagl_close'] = "</li>";
        $config['first_tag_open'] = "<li>";
        $config['first_tagl_close'] = "</li>";
        $config['last_tag_open'] = "<li>";
        $config['last_tagl_close'] = "</li>";

        $this->pagination->initialize($config);
        $data['link'] = $this->pagination->create_links();

        //$data['custom_js'] = 'public/admin/custom_js/category.js';
        $this->load->view('admin/layout', $data);
    }

    public function add() {
        $data['error'] = array();
        if ($this->input->server('REQUEST_METHOD') == 'POST') {
            //validate
            $this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[5]|is_unique[product.name]');
            $this->form_validation->set_rules('category_id', 'Category ID', 'trim|required|numeric');
            $this->form_validation->set_rules('quality', 'Quality', 'trim|required|numeric');
            $this->form_validation->set_rules('price', 'Price', 'trim|required|numeric');
            $this->form_validation->set_rules('discount', 'Discount', 'trim|required|numeric');
            $this->form_validation->set_rules('description', 'Description', 'trim|required');
            $this->form_validation->set_rules('content', 'Content', 'trim|required');
            $this->form_validation->set_error_delimiters('<div class="alert alert-danger"><strong>', '</strong></div>');
            if ($this->form_validation->run()) {
                $this->upload->initialize($this->setUploadOptions('thumbnail'));
                //upload thumbnail
                if (!$this->upload->do_upload("thumbnail")) {
                    $data['error'][] = $this->upload->display_errors();
                } else {
                    $thumbnail = $this->upload->data()['file_name'];
                }
                //upload images
                $files = $_FILES;
                $countFile = count($_FILES["images"]["name"]);
                $images = array();
                if ($countFile > 0) {
                    for ($i = 0; $i < $countFile; $i++) {
                        $_FILES['images']['name'] = $files['images']['name'][$i];
                        $_FILES['images']['type'] = $files['images']['type'][$i];
                        $_FILES['images']['tmp_name'] = $files['images']['tmp_name'][$i];
                        $_FILES['images']['error'] = $files['images']['error'][$i];
                        $_FILES['images']['size'] = $files['images']['size'][$i];

                        $this->upload->initialize($this->setUploadOptions('images'));
                        if (!$this->upload->do_upload('images')) {
                            $data['error'][] = $this->upload->display_errors();
                        } else {
                            //lấy dữ liệu file sau khi upload
                            $images[] = $this->upload->data()['file_name'];
                        }
                    }
                }
                $data_insert = $this->getDataInput();
                $slug = slugify($data_insert["name"]);
                $data_insert["slug"] = $slug;
                $data_insert["thumbnail"] = $thumbnail;
                if (count($images) > 0) {
                    $data_insert["images"] = json_encode($images);
                }
                if (isset($data_insert["hot"])) {
                    $data_insert["hot"] = 1;
                } else {
                    $data_insert["hot"] = 0;
                }
                if ($this->Product_model->create($data_insert)) {
                    $this->History_model->create(['content' => 'Thêm mới sản phẩm <strong>' . $data_insert['name'].'</strong>']);
                    $msg = alert_success("Add new <strong>".$data_insert['name']."</strong> product");
                    $this->session->set_flashdata("msg", $msg);
                    redirect("admin/product", 'refresh');
                }
                die;

                if (count($data['error']) > 0) {
                    
                }
            } else {
                
            }
        }
        $data['title'] = 'Product - Add';
        $data['content'] = 'admin/product/add';
        $data['categories'] = $this->Category_model->get_list();
        $this->load->view('admin/layout', $data);
    }

    public function edit($id = 0) {
        $data['title'] = 'Product - Edit';
        $data['content'] = 'admin/product/edit';
        // $data['categories'] = $this->Category_model->get_list();

        if ($id != 0) {
            $rules = [
                'product.id' => $id
            ];
            $product = $this->Product_model->getProducts(0, 0, $rules);
        }

        if ($this->input->server('REQUEST_METHOD') == 'POST') {
            //validate
            $this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[5]');
            $this->form_validation->set_rules('category_id', 'Category ID', 'trim|required|numeric');
            $this->form_validation->set_rules('quality', 'Quality', 'trim|required|numeric');
            $this->form_validation->set_rules('price', 'Price', 'trim|required|numeric');
            $this->form_validation->set_rules('discount', 'Discount', 'trim|required|numeric');
            $this->form_validation->set_rules('description', 'Description', 'trim|required');
            $this->form_validation->set_rules('content', 'Content', 'trim|required');
            $this->form_validation->set_error_delimiters('<div class="alert alert-danger"><strong>', '</strong></div>');
            if ($this->form_validation->run()) {
                $data = $this->getDataInput();

                //Kiểm tra xem người dùng có thay đổi thumbnail
                if (!isset($_FILES['thumbnail']) || $_FILES['thumbnail']['error'] == UPLOAD_ERR_NO_FILE) {
                    
                } else {
                    $thumbnail_old = $this->Product_model->getImage($id, 'thumbnail')->thumbnail;
                    $this->upload->initialize($this->setUploadOptions('thumbnail'));
                    //upload thumbnail
                    if (!$this->upload->do_upload("thumbnail")) {
                        $data['error'][] = $this->upload->display_errors();
                    } else {
                        $thumbnail_new = $this->upload->data()['file_name'];
                        if (file_exists(product_url() . $thumbnail_old)) {
                            if (unlink(product_url() . $thumbnail_old)) {
                                $data['thumbnail'] = $thumbnail_new;
                            }
                        }
                    }
                }

                if (!file_exists($_FILES['images']['tmp_name'][0])) {
                    
                } else {
                    //upload images
                    $files = $_FILES;
                    $countFile = count($_FILES["images"]["name"]);
                    $images = array();
                    if ($countFile > 0) {
                        for ($i = 0; $i < $countFile; $i++) {
                            $_FILES['images']['name'] = $files['images']['name'][$i];
                            $_FILES['images']['type'] = $files['images']['type'][$i];
                            $_FILES['images']['tmp_name'] = $files['images']['tmp_name'][$i];
                            $_FILES['images']['error'] = $files['images']['error'][$i];
                            $_FILES['images']['size'] = $files['images']['size'][$i];

                            $this->upload->initialize($this->setUploadOptions('images'));
                            if (!$this->upload->do_upload('images')) {
                                $data['error'][] = $this->upload->display_errors();
                            } else {
                                //lấy dữ liệu file sau khi upload
                                $images[] = $this->upload->data()['file_name'];
                            }
                        }
                    }
                    if (count($images) > 0) {
                        $image_old = json_decode($this->Product_model->getImage($id, 'images')->images, TRUE);
                        if (count($image_old) > 0) {
                            foreach ($image_old as $value) {
                                $images[] = $value;
                            }
                        }
                        $data["images"] = json_encode($images);
                    }
                }
                if (isset($data["hot"])) {
                    $data["hot"] = 1;
                } else {
                    $data["hot"] = 0;
                }
                $slug = slugify($data["name"]);
                $data_insert["slug"] = $slug;

                if ($this->Product_model->update($id, $data)) {
                    $this->History_model->create(['content' => 'Edit ' . '<strong>' . $data['name'] . '</strong> product']);
                    $msg = alert_success("Edit success");
                } else {
                    $msg = alert_danger("Edit fail");
                }
                $this->session->set_flashdata("msg", $msg);
                redirect("admin/product", "refresh");
            }
        }
        $data["product"] = $product;
        $data['categories'] = $this->Category_model->get_list();
        $this->load->view('admin/layout', $data);
    }

    public function delete($id = 0) {
        if ($id > 0) {
            $product = $this->Product_model->get_info($id);
            $name_product = $product->name;
            if ($product) {
                if (file_exists(product_url() . $product->thumbnail)) {
                    unlink(product_url() . $product->thumbnail);
                }
                if ($product->images) {
                    foreach (json_decode($product->images, TRUE) as $value) {
                        if (file_exists(product_url() . $value)) {
                            unlink(product_url() . $value);
                        }
                    }
                }
                if ($this->Product_model->delete($id)) {
                    $msg = alert_success("Delete success");
                } else {
                    $msg = alert_warning("Delete fail");
                }
                $this->session->set_flashdata("msg", $msg);
                $this->History_model->create(['content' => "Delete <strong>$name_product</strong> product"]);
                redirect("admin/product", "refresh");
            } else {
                
            }
        }
    }

    public function deleteimage() {

        if ($this->input->server('REQUEST_METHOD') == 'POST') {
            $data = $this->getDataInput();
            $image = $data['name'];
            $images = json_decode($this->Product_model->getImage($data['id'], 'images')->images, TRUE);
            log_message('error', '1');
            if (in_array($image, $images)) {
                log_message('error', '2');
                if (file_exists(product_url() . $image)) {
                    if (unlink(product_url() . $image)) {
                        unset($images[array_search($image, $images)]);
                        if ($this->Product_model->update($data['id'], ['images' => json_encode($images)])) {
                            $status = 'success';
                        } else {
                            $status = 'fail';
                        }
                    } else {
                        $status = 'fail';
                    }
                } else {
                    $status = 'fail';
                }
            } else {
                $status = 'fail';
            }
            $return = [
                'status' => $status
            ];
            echo json_encode($return);
        }
    }

    /* Cấu hình upload file */

    public function setUploadOptions($filename = NULL) {
        $config['upload_path'] = './public/uploads/product';
        $config['allowed_types'] = 'gif|jpg|png|jpeg';
        $config['overwrite'] = FALSE;
        if ($filename != NULL) {
            $config['file_name'] = time() . $_FILES[$filename]['name'];
        }
        return $config;
    }

    public function getDataInput() {
        return $this->input->post();
    }

}
