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

class Products_model extends CI_Model
{

    public function getProducts($number, $offset)
    {
        $this->db->select("*, products.id AS productsId, products.title AS productsTitle, products.price AS productsPrice, products.stock AS productsStock, products.date_submit AS productsDate, products.img AS productsImg, products.publish AS productsPublish, categories.name AS categoriesName, products.slug AS slugP");
        $this->db->join("categories", "products.category=categories.id");
        $this->db->order_by("products.id", "desc");
        return $this->db->get("products", $number, $offset);
    }

    public function getAllProducts($start)
    {
        $this->db->where('publish', 1);
        $this->db->order_by('id', 'desc');
        $this->db->limit(12, $start);
        return $this->db->get('products');
    }

    public function getRating($product, $number, $offset)
    {
        $this->db->order_by('id', 'desc');
        $this->db->where('product', $product);
        $this->db->where('active', 1);
        return $this->db->get('rating', $number, $offset);
    }

    public function getSearchProducts($key, $number, $offset)
    {
        $this->db->select("*, products.id AS productsId, products.title AS productsTitle, products.price AS productsPrice, products.stock AS productsStock, products.date_submit AS productsDate, products.img AS productsImg, products.publish AS productsPublish, categories.name AS categoriesName, products.slug AS slugP");
        $this->db->join("categories", "products.category=categories.id");
        $this->db->like("products.title", $key);
        $this->db->or_like("products.price", $key);
        $this->db->or_like("categories.name", $key);
        $this->db->order_by('products.id', 'desc');
        return $this->db->get('products', $number, $offset);
    }

    public function rowRatingByProduct($product)
    {
        $this->db->select_avg('star');
        $this->db->where('product', $product);
        $this->db->where('active', 1);
        $result = $this->db->get('rating');
        return $result->row_array()['star'] * 1;
    }

    public function totalTransactionProduct($slug)
    {
        $transaction = $this->db->get_where('transaction', ['slug' => $slug]);
        $total = 0;
        foreach ($transaction->result_array() as $tr) {
            $order = $this->db->get_where('invoice', ['invoice_code' => $tr['id_invoice']])->row_array();
            if ($order['status'] == 3) {
                $total += $tr['qty'];
            }
        }
        return $total;
    }

    public function getAllProductBestSeller($start)
    {
        $this->db->where('publish', 1);
        $this->db->order_by('transaction', 'desc');
        $this->db->limit(12, $start);
        return $this->db->get('products');
    }

    public function getRelatedProduct($category, $limit)
    {
        $this->db->where('category', $category);
        $this->db->where('publish', 1);
        $this->db->order_by('stock', "asc");
        $this->db->order_by('transaction', "asc");
        $this->db->order_by('viewer', "asc");
        $this->db->limit($limit);
        return $this->db->get('products');
    }

    public function searchProducts($q, $type = "")
    {
        if ($type == "") {
            $this->db->where('publish', 1);
            $this->db->like('title', $q);
            return $this->db->get('products');
        } else if ($type == "az") {
            $this->db->where('publish', 1);
            $this->db->order_by('title', 'asc');
            $this->db->like('title', $q);
            return $this->db->get('products');
        } else if ($type == "za") {
            $this->db->where('publish', 1);
            $this->db->order_by('title', 'desc');
            $this->db->like('title', $q);
            return $this->db->get('products');
        } else if ($type == "pricemax") {
            $this->db->where('publish', 1);
            $this->db->order_by('price', 'asc');
            $this->db->like('title', $q);
            return $this->db->get('products');
        } else if ($type == "pricemin") {
            $this->db->where('publish', 1);
            $this->db->order_by('price', 'desc');
            $this->db->like('title', $q);
            return $this->db->get('products');
        } else if ($type == "promo") {
            $this->db->where('publish', 1);
            $this->db->where('promo_price != 0');
            $this->db->like('title', $q);
            return $this->db->get('products');
        } else if ($type == "1") {
            $this->db->where('publish', 1);
            $this->db->where('condit', 1);
            $this->db->like('title', $q);
            return $this->db->get('products');
        } else if ($type == "2") {
            $this->db->where('publish', 1);
            $this->db->where('condit', 2);
            $this->db->like('title', $q);
            return $this->db->get('products');
        }
    }

    public function searchProductsPrice($q, $min, $max)
    {
        if ($max == "0") {
            $this->db->where('publish', 1);
            $this->db->where('price >=', $min);
            $this->db->like('title', $q);
            return $this->db->get('products');
        } else {
            $this->db->where('publish', 1);
            $this->db->where('price >=', $min);
            $this->db->where('price <=', $max);
            $this->db->like('title', $q);
            return $this->db->get('products');
        }
    }

    public function getAllProductsByCategory($c, $start, $sort)
    {
        $this->db->where('publish', 1);
        $this->db->where('category', $c);
        if ($sort == "bestseller") {
            $this->db->order_by('transaction', 'desc');
        } else if ($sort == "latest") {
            $this->db->order_by('id', 'desc');
        } else if ($sort == "cheapest") {
            $this->db->order_by('price', 'asc');
        } else if ($sort == "expensive") {
            $this->db->order_by('price', 'desc');
        } else if ($sort == "") {
            $this->db->order_by('id', 'desc');
        }
        $this->db->limit(12, $start);
        return $this->db->get('products');
    }

    public function getAllProductsPrice($min, $max)
    {
        if ($max == "0") {
            $this->db->where('publish', 1);
            $this->db->where('price >=', $min);
            return $this->db->get('products');
        } else {
            $this->db->where('publish', 1);
            $this->db->where('price >=', $min);
            $this->db->where('price <=', $max);
            return $this->db->get('products');
        }
    }

    public function getAllProductsByCategoryPrice($cat, $min, $max)
    {
        if ($max == "0") {
            $this->db->where('publish', 1);
            $this->db->where('category', $cat);
            $this->db->where('price >=', $min);
            return $this->db->get('products');
        } else {
            $this->db->where('publish', 1);
            $this->db->where('category', $cat);
            $this->db->where('price >=', $min);
            $this->db->where('price <=', $max);
            return $this->db->get('products');
        }
    }

    public function getImgProductBySlug($slug)
    {
        $product = $this->db->get_where('products', ['slug' => $slug])->row_array();
        return $this->db->get_where('img_product', ['id_product' => $product['id']]);
    }

    public function getProductsLimit($start)
    {
        $this->db->where('publish', 1);
        $this->db->order_by("id", "desc");
        $this->db->limit(8, $start);
        return $this->db->get("products");
    }

    public function getBestProductsLimit()
    {
        $this->db->select("*");
        $this->db->from("products");
        $this->db->order_by("transaction", "desc");
        $this->db->limit(4);
        $this->db->where('publish', 1);
        return $this->db->get();
    }

    public function getTransactionByInvoice($id)
    {
        return $this->db->get_where('transaction', ['id_invoice' => $id]);
    }

    public function getProductById($id)
    {
        $this->db->select("*,products.id AS productId, products.slug AS slugP");
        $this->db->from("products");
        $this->db->join("categories", "products.category=categories.id");
        $this->db->order_by("products.id", "desc");
        $this->db->where('products.id', $id);
        return $this->db->get()->row_array();
    }

    public function getProductBySlug($slug)
    {
        $this->db->select("*,products.id AS productId, categories.slug AS cSlug, products.slug AS slugP");
        $this->db->from("products");
        $this->db->join("categories", "products.category=categories.id");
        $this->db->order_by("products.id", "desc");
        $this->db->where('products.slug', $slug);
        return $this->db->get()->row_array();
    }

    function resize_crop($config, $resize_width, $resize_height)
    {
        if ($config) {
            $CI = &get_instance();
            $CI->load->library('image_lib');

            $img_size = getimagesize($config['source_image']);

            $t_ratio = $resize_width / $resize_height;
            $o_width = $img_size[0];
            $o_height = $img_size[1];
            if ($t_ratio > $o_width / $o_height) {
                $config['width'] = $resize_width;
                $config['height'] = round($resize_width * ($o_height / $o_width));
                $y_axis = round(($config['height'] / 2) - ($resize_height / 2));
                $x_axis = 0;
            } else {
                $config['width'] = round($resize_height * ($o_width / $o_height));
                $config['height'] = $resize_height;
                $y_axis = 0;
                $x_axis = round(($config['width'] / 2) - ($resize_width / 2));
            }

            $source_img01 = $config['new_image'];

            $CI->image_lib->clear();
            $CI->image_lib->initialize($config);
            $CI->image_lib->resize();

            $config['image_library'] = 'gd2';
            $config['source_image'] = $source_img01;
            $config['create_thumb'] = false;
            $config['maintain_ratio'] = false;
            $config['width'] = $resize_width;
            $config['height'] = $resize_height;
            $config['y_axis'] = $y_axis;
            $config['x_axis'] = $x_axis;

            $CI->image_lib->clear();
            $CI->image_lib->initialize($config);
            $CI->image_lib->crop();

            return $config['new_image'];
        }
        return FALSE;
    }

    public function uploadImg()
    {
        $config['upload_path'] = './assets/images/product/';
        $config['allowed_types'] = 'jpg|png|jpeg|image/png|image/jpg|image/jpeg';
        $config['max_size'] = '2048';
        $config['file_name'] = round(microtime(true) * 1000);

        $this->load->library('upload', $config);
        if ($this->upload->do_upload('img')) {
            $gbr = $this->upload->data();
            $config['image_library'] = 'gd2';
            $config['source_image'] = './assets/images/product/' . $gbr['file_name'];
            $config['new_image'] = './assets/images/product/' . $gbr['file_name'];
            $this->resize_crop($config, '600', '600');
            $return = array('result' => 'success', 'file' => $this->upload->data(), 'error' => '');
            return $return;
        } else {
            $return = array('result' => 'failed', 'file' => '', 'error' => $this->upload->display_errors());
            return $return;
        }
    }

    public function insertImg($upload, $id)
    {
        $data = [
            'id_product' => $id,
            'img' => $upload['file']['file_name']
        ];
        $this->db->insert('img_product', $data);
    }

    public function insertProduct($upload)
    {
        $idProduct = $this->db->query('SELECT * FROM products ORDER BY id DESC LIMIT 1')->row_array()['id'] + 1;
        $title = $this->input->post('title');
        $category = $this->input->post('category');
        $stock = $this->input->post('stock');
        $weight = $this->input->post('weight');
        $price = $this->input->post('price');
        $discount = $this->input->post('discount');
        $description = $this->input->post('description');
        $img = $upload['file']['file_name'];
        $date_submit = date("Y-m-d H:i:s");
        $publish = $this->input->post('publish');
        $variant_name = $this->input->post('variant_name');
        function textToSlug($text = '')
        {
            $text = trim($text);
            if (empty($text)) return '';
            $text = preg_replace("/[^a-zA-Z0-9\-\s]+/", "", $text);
            $text = strtolower(trim($text));
            $text = str_replace(' ', '-', $text);
            $text = $text_ori = preg_replace('/\-{2,}/', '-', $text);
            return $text;
        }
        $slug = textToSlug($title) . time();
        $data = [
            "id" => $idProduct,
            "title" => $title,
            "category" => $category,
            "stock" => $stock,
            "weight" => $weight,
            "price" => $price,
            "discount" => $discount,
            "description" => $description,
            "publish" => $publish,
            "img" => $img,
            "date_submit" => $date_submit,
            "slug" => $slug,
            "variant_name" => $variant_name,
        ];
        $insertProduct = $this->db->insert('products', $data);

        $variant_type = $this->input->post('variant_type');
        $variant_price = $this->input->post('variant_price');
        foreach ($variant_type as $key => $value) {
            if ($_POST['variant_type'][$key] != "" && $_POST['variant_price'][$key] != "") {
                $result = [
                    'product' => $idProduct,
                    'type' => $_POST['variant_type'][$key],
                    'price' => $_POST['variant_price'][$key],
                ];
                $this->db->insert('variant', $result);
            }
        }

        $wholesaler = $this->input->post('wholesaler_count');
        foreach ($wholesaler as $key => $value) {
            if ($_POST['wholesaler_count'][$key] != "" && $_POST['wholesaler_price'][$key] != "") {
                $result = [
                    'id_product' => $idProduct,
                    'count' => $_POST['wholesaler_count'][$key],
                    'price' => $_POST['wholesaler_price'][$key],
                ];
                $this->db->insert('wholesaler', $result);
            }
        }

        $color = $this->input->post('color');
        $dataColor = explode(",", $color);
        foreach ($dataColor as $key => $value) {
            if ($dataColor[$key] != "") {
                $data = [
                    'product' => $idProduct,
                    'color' => $dataColor[$key]
                ];
                $this->db->insert('color_product', $data);
            }
        }

        $gallery = $this->input->post('gallery');
        $config['upload_path'] = './assets/images/product/';
        $config['allowed_types'] = 'jpg|png|jpeg|image/png|image/jpg|image/jpeg';
        $config['max_size'] = '2048';
        $config['file_name'] = round(microtime(true) * 1000);
        $this->load->library('upload', $config);
        for ($i = 1; $i < 5; $i++) {
            if (!empty($_FILES['gallery' . $i]['name'])) {
                if (!$this->upload->do_upload('gallery' . $i)) {
                    $this->upload->display_errors();
                } else {
                    $gbr = $this->upload->data();
                    $config['image_library'] = 'gd2';
                    $config['source_image'] = './assets/images/product/' . $gbr['file_name'];
                    $config['new_image'] = './assets/images/product/' . $gbr['file_name'];
                    $this->resize_crop($config, '600', '600');
                    $data = [
                        'id_product' => $idProduct,
                        'img' => $this->upload->data()['file_name'],
                        'sort' => $i
                    ];
                    $this->db->insert('img_product', $data);
                }
            }
        }
    }

    public function updateProduct($upload, $id)
    {
        $title = $this->input->post('title');
        $category = $this->input->post('category');
        $stock = $this->input->post('stock');
        $weight = $this->input->post('weight');
        $price = $this->input->post('price');
        $discount = $this->input->post('discount');
        $description = $this->input->post('description');
        $publish = $this->input->post('publish');
        $variant_name = $this->input->post('variant_name');
        if ($upload == "") {
            $data = [
                "title" => $title,
                "category" => $category,
                "stock" => $stock,
                "weight" => $weight,
                "price" => $price,
                "discount" => $discount,
                "description" => $description,
                "publish" => $publish,
                "variant_name" => $variant_name,
            ];
        } else {
            $data = [
                "title" => $title,
                "category" => $category,
                "stock" => $stock,
                "weight" => $weight,
                "price" => $price,
                "img" => $upload['file']['file_name'],
                "discount" => $discount,
                "description" => $description,
                "publish" => $publish,
                "variant_name" => $variant_name,
            ];
        }
        $this->db->where('id', $id);
        $insertProduct = $this->db->update('products', $data);
        $idProduct = $id;

        $this->db->where('product', $idProduct);
        $this->db->delete('variant');
        $variant_type = $this->input->post('variant_type');
        $variant_price = $this->input->post('variant_price');
        foreach ($variant_type as $key => $value) {
            if ($_POST['variant_type'][$key] != "" && $_POST['variant_price'][$key] != "") {
                $result = [
                    'product' => $idProduct,
                    'type' => $_POST['variant_type'][$key],
                    'price' => $_POST['variant_price'][$key],
                ];
                $this->db->insert('variant', $result);
            }
        }

        $this->db->where('id_product', $id);
        $this->db->delete('wholesaler');
        $wholesaler = $this->input->post('wholesaler_count');
        foreach ($wholesaler as $key => $value) {
            if ($_POST['wholesaler_count'][$key] != "" && $_POST['wholesaler_price'][$key] != "") {
                $result = [
                    'id_product' => $idProduct,
                    'count' => $_POST['wholesaler_count'][$key],
                    'price' => $_POST['wholesaler_price'][$key],
                ];
                $this->db->insert('wholesaler', $result);
            }
        }

        $this->db->where('product', $idProduct);
        $this->db->delete('color_product');

        $color = $this->input->post('color');
        $dataColor = explode(",", $color);
        foreach ($dataColor as $key => $value) {
            if ($dataColor[$key] != "") {
                $data = [
                    'product' => $idProduct,
                    'color' => $dataColor[$key]
                ];
                $this->db->insert('color_product', $data);
            }
        }

        $config['upload_path'] = './assets/images/product/';
        $config['allowed_types'] = 'jpg|png|jpeg|image/png|image/jpg|image/jpeg';
        $config['max_size'] = '2048';
        $config['file_name'] = round(microtime(true) * 1000);
        $this->load->library('upload', $config);
        for ($i = 1; $i < 5; $i++) {
            if (!empty($_FILES['gallery' . $i]['name'])) {
                if (!$this->upload->do_upload('gallery' . $i)) {
                    $this->upload->display_errors();
                } else {
                    $gbr = $this->upload->data();
                    $config['image_library'] = 'gd2';
                    $config['source_image'] = './assets/images/product/' . $gbr['file_name'];
                    $config['new_image'] = './assets/images/product/' . $gbr['file_name'];
                    $this->resize_crop($config, '600', '600');
                    $this->db->where('sort', $i);
                    $this->db->where('id_product', $idProduct);
                    $this->db->delete('img_product');
                    $data = [
                        'id_product' => $idProduct,
                        'img' => $this->upload->data()['file_name'],
                        'sort' => $i
                    ];
                    $this->db->insert('img_product', $data);
                }
            }
        }
    }

    public function updateViewer($slug)
    {
        $result = $this->db->get_where('products', ['slug' => $slug])->row_array();
        $newV = (int)$result['viewer'] + 1;
        $this->db->set('viewer', $newV);
        $this->db->where('id', $result['id']);
        $this->db->update('products');
    }
}
