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

class Product extends CI_Controller {

    public function __construct() {
        parent::__construct();
        date_default_timezone_set("Asia/Kolkata");
        $this->load->model('Brand_model');
        $this->load->model('Product_model');
        $this->load->model('Vehicle_model');
        if(!$this->session->userdata('logged_in')) {
            redirect(base_url('Login'));
        }
    }

    public function addProduct(){
        $template['page'] = 'Product/addproduct';
        $template['pTitle'] = "Add Product";
        $template['pDescription'] = "Add Product"; 
        $template['menu'] = "Product Management";
        $template['smenu'] = "View Product";
        $template['brand_id'] = '';
        $template['product_data'] = $this->Product_model->getProduct();
        $template['veh_data']['make'] = $this->Vehicle_model->getVehBrand('',1);
        $template['veh_data']['model'] = $this->Vehicle_model->getVehModel('',1);
        $template['brand_data'] = $this->Brand_model->getbrand('',1);
        $this->load->view('template',$template);
    }

    public function viewProducts(){
        $template['page'] = 'Product/viewProduct';
        $template['menu'] = 'Product Management';
        $template['smenu'] = 'View Product';
        $template['pTitle'] = "View Product";
        $template['pDescription'] = "View and Manage Product";
        $mechanic_id = ($this->session->userdata['user_type']==2)?$this->session->userdata['id']:'';
        $template['product_data'] = $this->Product_model->getProduct('',1,$mechanic_id);
        $this->load->view('template',$template);
    }

    function changeStatus($brand_id = '',$status = '1'){
        $flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
        if(empty($brand_id) || !is_numeric($brand_id = decode_param($brand_id))){
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('brand/viewProducts'));
        }
        $status = $this->Product_model->changeStatus($brand_id,$status);
        if(!$status){
            $this->session->set_flashdata('message',$flashMsg);
        }
        redirect(base_url('Product/viewProducts'));
    }

    public function createproduct(){
        $err = 0;
        $errMsg = '';
        $flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
        if(!isset($_POST) || empty($_POST)){
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Product/addproduct'));
        }
        if($err == 0 && (!isset($_POST['brand_id']) || empty($_POST['brand_id']))){
            $err = 1;
            $errMsg = 'Please Select a Brand';
        }else if($err == 0 && (!isset($_POST['short_description']) || empty($_POST['short_description']))){
            $err = 1;
            $errMsg = 'Provide a short Description';
        }else if($err == 0 && (!isset($_POST['product_name']) || empty($_POST['product_name']))){
            $err = 1;
            $errMsg = 'Provide a Product Name';
        }else if($err == 0 && (!isset($_POST['description']) || empty($_POST['description']))){
            $err = 1;
            $errMsg = 'Provide a Description';
        }else if($err == 0 && (!isset($_POST['about']) || empty($_POST['about']))){
            $err = 1;
            $errMsg = 'Provide a About';
        }else if($err == 0 && (!isset($_POST['amount']) || empty($_POST['amount']))){
            $err = 1;
            $errMsg = 'Provide a Amount';
         }
        if($err == 1){
            $flashMsg['message'] = $errMsg;
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Product/addproduct'));
        }
        $_POST['created_by']=($this->session->userdata['user_type']==2)?$this->session->userdata['id']:0;
        $product_id = $this->Product_model->addProduct($_POST);
        if($product_id){
            $evtMediaData = array();
            if(!empty($files = $_FILES)){
                $images = array();
                $this->load->library('upload');
                $config = set_upload_service("assets/uploads/products");
                for ($typ = 0; $typ < count($files['product_image']['name']); $typ++) { 
                    $_FILES['file']['name'] = $files['product_image']['name'][$typ];
                    $_FILES['file']['type'] = $files['product_image']['type'][$typ];
                    $_FILES['file']['size'] = $files['product_image']['size'][$typ]; 
                    $_FILES['file']['error'] = $files['product_image']['error'][$typ];
                    $_FILES['file']['tmp_name'] = $files['product_image']['tmp_name'][$typ];
                    $config['file_name'] = time()."_".$_FILES['file']['name'];
                    $this->upload->initialize($config);
                    if($this->upload->do_upload('file')){
                        $imgData = $this->upload->data();
                        $evtMediaData[] = array(
                                            'product_id'=>$product_id,
                                            'image'=>"assets/uploads/products/".$imgData['file_name']);
                    }
                }
                $status = $this->Product_model->addProductImage($evtMediaData);
            }
            if($status == 1 || $product_id){
                $flashMsg =array('message'=>'Successfully Updated brand Details..!','class'=>'success');
                $this->session->set_flashdata('message', $flashMsg);
                redirect(base_url('Product/viewProducts'));
            }else {
                $this->session->set_flashdata('message', $flashMsg);
                redirect(base_url('Product/addproduct'));
            }
        }
    }

    public function editproduct($product_id){
        $flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
        if(empty($product_id) || !is_numeric($product_id = decode_param($product_id))){
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Product/viewProducts'));
        }
        $template['page'] = 'Product/addproduct';
        $template['menu'] = 'Brand Management';
        $template['smenu'] = 'Edit brand';
        $template['pTitle'] = "Edit brand";
        $template['pDescription'] = "Update brand Data";
        $template['product_id'] = encode_param($product_id);
        $template['brand_data'] = $this->Brand_model->getbrand('',1);
        $template['product_data'] = $this->Product_model->getProduct($product_id);
        $template['veh_data']['make'] = $this->Vehicle_model->getVehBrand('',1);
        $template['product_image'] = $this->Product_model->getProductImage($product_id);
        $template['brand_id'] = $template['product_data']->brand_id;
        $this->load->view('template',$template);
    }

    public function updateproduct($product_id = ''){
        $err = 0;
        $errMsg = '';
        $flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
        if(empty($product_id) || !isset($_POST) || empty($_POST) || !is_numeric(decode_param($product_id))){
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Product/viewProducts'));
        }
        if(!isset($_POST) || empty($_POST)){
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Product/addproduct'));
        }
        if($err == 0 && (!isset($_POST['brand_id']) || empty($_POST['brand_id']))){
            $err = 1;
            $errMsg = 'Please Select a Brand';
        }else if($err == 0 && (!isset($_POST['short_description']) || empty($_POST['short_description']))){
            $err = 1;
            $errMsg = 'Provide a short Description';
        }else if($err == 0 && (!isset($_POST['product_name']) || empty($_POST['product_name']))){
            $err = 1;
            $errMsg = 'Provide a Product Name';
        }else if($err == 0 && (!isset($_POST['description']) || empty($_POST['description']))){
            $err = 1;
            $errMsg = 'Provide a Description';
        }else if($err == 0 && (!isset($_POST['about']) || empty($_POST['about']))){
            $err = 1;
            $errMsg = 'Provide a About';
        }else if($err == 0 && (!isset($_POST['amount']) || empty($_POST['amount']))){
            $err = 1;
            $errMsg = 'Provide a Amount';
        }
        if($err == 1){
            $flashMsg['message'] = $errMsg;
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Product/addproduct'));
        }
        $existingImages = (isset($_POST['existingImages']) && !empty($_POST['existingImages']))?
                              $_POST['existingImages']:'';
        unset($_POST['existingImages']);
        $product = $this->Product_model->updateProduct(decode_param($product_id),$_POST);
        if($product){
            $evtMediaData = array();
            if(!empty($files = $_FILES)){
                $images = array();
                $this->load->library('upload');
                $config = set_upload_service("assets/uploads/products");
                for ($typ = 0; $typ < count($files['product_image']['name']); $typ++) { 
                    $_FILES['file']['name'] = $files['product_image']['name'][$typ];
                    $_FILES['file']['type'] = $files['product_image']['type'][$typ];
                    $_FILES['file']['size'] = $files['product_image']['size'][$typ]; 
                    $_FILES['file']['error'] = $files['product_image']['error'][$typ];
                    $_FILES['file']['tmp_name'] = $files['product_image']['tmp_name'][$typ];
                    $config['file_name'] = time()."_".$_FILES['file']['name'];
                    $this->upload->initialize($config);
                    if($this->upload->do_upload('file')){
                        $imgData = $this->upload->data();
                        $evtMediaData[] = array(
                                            'product_id'=>decode_param($product_id),
                                            'image'=>"assets/uploads/products/".$imgData['file_name']);
                    }
                }
                $status = $this->Product_model->updateProductImage(decode_param($product_id),$evtMediaData,$existingImages);
            }
        }
        if($status || $product){
            $flashMsg =array('message'=>'Successfully Updated brand Details..!','class'=>'success');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Product/viewProducts'));
        } else {
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Product/editproduct/'.$brand_id));
        }
    }

    public function getProductData(){
        $return_arr = array('status'=>'0');
        if(!isset($_POST) || empty($_POST) || !isset($_POST['product_id']) || empty($_POST['product_id']) || empty(decode_param($_POST['product_id']))){
            echo json_encode($return_arr);exit;
        }
        $product_id = decode_param($_POST['product_id']);
        $return_arr['product_data'] = $this->Product_model->getProduct($product_id);
        $return_arr['product_image'] = $this->Product_model->getProductImage($product_id);
        if(!empty($return_arr)){
            $return_arr['status'] = 1;
            echo json_encode($return_arr);exit;
        }
        echo json_encode($return_arr);exit;
    }

    public function exportProductData(){
        $mechanic_id = ($this->session->userdata['user_type']==2)?$this->session->userdata['id']:'';
        $productData = $this->Product_model->getProduct('',1,$mechanic_id);
        if(empty($productData)){
            return;
        }
        $header = array('Product ID','Product Name','Brand Name','Short Description','Part ID','Vehicle Model','Amount','Status');
        $file = 'productData_'.time().'.csv';
        $fpoint = fopen('php://memory', 'w');
        fputcsv($fpoint, $header, ',');
        foreach($productData AS $product){
            $data = array();
            $status = 'Active';
            switch ($product->status) {
                case '0': $status = 'Inactive';break;
                case '1': $status = 'Active ';break;
                case '2': $status = 'Deleted';break;
            }
            $data[] = $product->product_id;
            $data[] = $product->product_name;
            $data[] = $product->brand_name;
            $data[] = $product->short_description;
            $data[] = $product->part_id;
            $data[] = $product->model;
            $data[] = $product->amount;
            $data[] = $status;
            fputcsv($fpoint, $data, ',');
        }
        fseek($fpoint, 0);
        header('Content-Type: application/csv');
        header('Content-Disposition: attachement; filename="' . $file . '";');
        fpassthru($fpoint);
    }
}
?>