<?php

class Products   extends CI_Controller {
    
    var $tablename = PRODUCTS;
    var $primarykey = "ProductID";
        
    var $tablename2 = PRODUCTSJOIN;
    
    public function index(){               
        $data['current'] = "productmanage";        
        $this->load->view(ADMINFOLDER."/choosemethod",$data);
    }
    
    public function delete($id){        
        $newsRecord = $this->general->getRecordWhere($this->tablename, array("$this->primarykey"=>$id));
			if(count($newsRecord)){				                                                                                                                                      
                            
                                                if(file_exists("images/products/".$newsRecord->Picture)){
                                                @unlink("images/products/".$newsRecord->Picture);
                                                }
                                            
                                                if(file_exists("images/products/".$this->ImageProcess->returnThumb($newsRecord->Picture))){
                                                @unlink("images/products/".$this->ImageProcess->returnThumb($newsRecord->Picture));
                                                }
                                                
                                                
				$this->db->query("DELETE FROM ".$this->tablename." WHERE $this->primarykey = $id");                                                                                                
                                $this->db->query("DELETE FROM ".$this->tablename2." WHERE $this->primarykey = $id");                                                                                                
				$data['message'] = $this->general->generateMessage("Record Deleted Successfully !!!", "green");
			}else{
				$data['message'] = $this->general->generateMessage("No record found with the specified id.", "red");
			}        
                        
             $this->productslist();  
            
    }
    
    public function bulkadding(){               
        $data['current'] = "productmanage";     
        $this->load->library('form_validation');
        
        $this->form_validation->set_rules('txt_cat', 'Category List', 'trim');
        
        if ($this->form_validation->run() == TRUE)
	{             
                // do action of export sheet             
                $CID=$this->input->post("txt_cat");      
                // get field group ID
                $field = $this->general->getRecordWhere(CATEGORIES,array("CategoryID" => $CID), "CategoryID","desc");                
                // add custom fields to template.xlsx   
                $this->session->set_userdata("categoryID","$field->FGID");
                $this->excelupdate("template.xlsx",$field->FGID);                                                
        }
        
        $this->load->view(ADMINFOLDER."/choosecategory",$data);        
    }
    
    
    function uploadproducts()
    {
        $data['current'] = "uploadproducts";  
        $this->load->library('form_validation');
        
        $this->form_validation->set_rules('txt_file', 'Products List', 'trim');
        
        if ($this->form_validation->run() == TRUE)
	{
            
                      
            $filesname = "test.xsl";
            
            // read uploaded excel and add to database                
            $this->uploadexcel($filesname,"txt_file");
            
            // go to success page
            $this->productslist();            
           
            
        }
        else
        {
        $this->load->view(ADMINFOLDER."/uploadproducts",$data);
        }
    }
    
    
    function productslist()
    {        
         $data['current'] = "porductslist";  
         $permissionid = $this->session->userdata("UperId");
         $where = array();
         if($permissionid == 2)
            $where = array("SupplierID" => $permissionid); 
         $data['products'] = $this->general->getAllRecordsWhere(PRODUCTS,$where,"ProductID","desc");
         $this->load->view(ADMINFOLDER."/products",$data);
    }
    
    function uploadexcel($excelfile,$inputfield)
    {
        $file = './uploads/'.$excelfile;
 
        //load the excel library
        $this->load->library('excel');

        $path =  $_FILES["$inputfield"]["tmp_name"];
        
        //read file from path
        $objPHPExcel = PHPExcel_IOFactory::load($path);

        //get only the Cell Collection
        $cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();

        //extract to a PHP readable array format
        foreach ($cell_collection as $cell) {
            $column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
            $row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
            $data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();

            //The header will/should be in row 1 only. of course, this can be modified to suit your need.
            if ($row == 1) {
                $header[$row][$column] = $data_value;
                
            } else {
                $arr_data[$row][$column] = $data_value;
                
            }
        }

        // add data to database
        
        foreach ($arr_data as $row)
        {
            
            foreach($row as $head=>$cell)
            {                                        
                if($head >='A' & $head<='F')
                {
                    $savedata[$header[1][$head]] = $cell;
                }
                else
                {
                    $savedata2[$header[1][$head]] = $cell;
                }               
            }              
            
            // add new product to database
            $savedata["date_added"] = date("Y-m-d H:i:s");
            $savedata["date_modified"] = date("Y-m-d H:i:s");
            $savedata["SupplierID"] = $this->session->userdata("AdminID");
            $this->general->insertRecord($this->tablename, $savedata);    
            $productid = $this->db->insert_id();
            
            // get all custom fields and add to database
            $categoryID = $this->session->userdata("categoryID");
            $query = "select  f.FieldID, f.FieldLabel
                from ed_fieldscat fc
                LEFT JOIN
                ed_fieldscatjoin fj ON fc.FieldCatID = fj.CID
                LEFT JOIN ed_fields f ON fj.FID = f.FieldID
                where fc.FieldCatID = ".$categoryID;                
            $customfields = $this->general->get_query_result($query);
            foreach ($customfields as $cf)
            {
                $cfdata = array(
                    "ProductID"             => $productid,
                    "FieldID"               => $cf->FieldID,
                    "Value"                 => $savedata2[$cf->FieldLabel],
                    "added_by"              => $this->session->userdata("AdminID"),
                    "date_added"            => date("Y-m-d H:i:s"),
                    "date_modified"         => date("Y-m-d H:i:s")
                );
                
                $this->general->insertRecord($this->tablename2, $cfdata);   
            }                                     
        }
        
       
    }
    
    
    
    function excelupdate($excelfile,$categoryID)
    {
        
        //load the excel library
        $this->load->library('excel');
        
        $file = './uploads/'.$excelfile;
        
        //read file from path
        $objPHPExcel = PHPExcel_IOFactory::load($file);
        
                
        
        // add all custom fields depend on category  ======================
        
        $objPHPExcel->setActiveSheetIndex(0);        
        $characters = range('G', 'Z');
        
        
        $query = "select  f.FieldID, f.FieldLabel,f.FieldType
                from ed_fieldscat fc
                LEFT JOIN
                ed_fieldscatjoin fj ON fc.FieldCatID = fj.CID
                LEFT JOIN ed_fields f ON fj.FID = f.FieldID
                where fc.FieldCatID = ".$categoryID;
        
        
        $customfields = $this->general->get_query_result($query);
        $i=0;
        
        
        foreach ($customfields as $row)
        {
            $j = 1;
            $k = 2;
            
            $objPHPExcel->getActiveSheet()
            ->setCellValue($characters[$i].$j, $row->FieldLabel)
            ;
            
            if($row->FieldType == 1)
            {
            $objPHPExcel->getActiveSheet()
            ->setCellValue($characters[$i].$k, "SELECT ITEM")
            ;
            }
            
            // get related choices
            $query2 = "select  c.Choice
                        from ed_fieldschoices c
                        LEFT JOIN
                        ed_fieldschoicesjoin cj ON c.ChoiceID = cj.CHID
                        where cj.FID = ".$row->FieldID;
            $choices = $this->general->get_query_result($query2);
            foreach ($choices as $ro)
            {
                $dropdownlist .= $ro->Choice.", ";
            }
            
            if($row->FieldType == 1)
            {
            $objValidation = $objPHPExcel->getActiveSheet()->getCell($characters[$i].$k)->getDataValidation();
            $objValidation->setType( PHPExcel_Cell_DataValidation::TYPE_LIST );
            $objValidation->setErrorStyle( PHPExcel_Cell_DataValidation::STYLE_INFORMATION );
            $objValidation->setAllowBlank(false);
            $objValidation->setShowInputMessage(true);
            $objValidation->setShowErrorMessage(true);
            $objValidation->setShowDropDown(true);
            $objValidation->setErrorTitle('Input error');
            $objValidation->setError('Value is not in list.');
            $objValidation->setPromptTitle('Pick from list');
            $objValidation->setPrompt('Please pick a value from the drop-down list.');
            $objValidation->setFormula1('"'.$dropdownlist.'"');
            }
            $dropdownlist = "";
            
            $i++;
        }
        
        
              

        // ======================================================================
        
        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);

                       
        
        // download Excel Sheet
        $filename='uploads/products-'.date('d-m-Y').'-'.$this->session->userdata('AdminID').'.xls'; //save our workbook as this file name
        //header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); //mime type
       // header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
       // header('Cache-Control: max-age=0'); //no cache

        //save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
        //if you want to save it as .XLSX Excel 2007 format
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');          
        $objWriter->save($filename);
        
        //force user to download the Excel file 
        $this->load->helper('download');
        
        
        $file_content = file_get_contents($filename); // Read the file's contents
        if(file_exists($filename)){
            unlink($filename);
        }
        force_download($filename, $file_content);        
    }

    
    
   
    
            
    
    
    
    public function AddItem(){
        $this->load->library('form_validation');
         
        $this->form_validation->set_rules('txt_active', 'Is Active', 'trim');

        $data['message'] = "";
		
        if ($this->form_validation->run() == TRUE)
	{                        
            $updateData = array(
                "$this->primarykey" 	=> $id,
                "is_active"             => $this->input->post("txt_active"),                 
                "date_modified"         => date("Y-m-d H:i:s")
            );
                        
            $this->general->updateRecord($this->tablename, $updateData, "$this->primarykey");                                        
            $data['message'] = "Supplier updated successfully";
        }
            
        $data['record'] = $this->general->getRecordWhere($this->tablename,array("$this->primarykey"=>$id), "$this->primarykey","desc");    
        $this->load->view(ADMINFOLDER."/editsupplier",$data);
    }
    
    
    public function edititem($id){
        $this->load->library('form_validation');
         
        $this->form_validation->set_rules('txt_title', 'Title', 'required|trim');
        $this->form_validation->set_rules('txt_price', 'Price', 'required|trim');
        $this->form_validation->set_rules('txt_quantity', 'Quantity', 'required|trim');
        $this->form_validation->set_rules('txt_desc', 'Description', 'required|trim');
        
        $data['message'] = "";
		
        $query = "select  f.*, fv.*
        from ed_fields f
        LEFT JOIN
        ed_productfieldsvalues fv  ON f.FieldID = fv.FieldID        
        where fv.ProductID = ".$id;                
        $data['dfields'] = $this->general->get_query_result($query);
        
        if ($this->form_validation->run() == TRUE)
	{                    
            $slug = $this->general->SEF_URLS($this->input->post("txt_title"))."-".$id;
            $updateData = array(
                "$this->primarykey" 	=> $id,
                "ProductName"             => $this->input->post("txt_title"),                 
                "slug"             => $slug, 
                "ProductDescription"             => $this->input->post("txt_desc"),
                "UnitPrice"             => $this->input->post("txt_price"),
                "UnitsInStock"             => $this->input->post("txt_quantity"),
                "SKU"             => $this->input->post("txt_sku"),
                "is_active"             => $this->input->post("txt_active"),
                "date_modified"         => date("Y-m-d H:i:s")
            );
                                                
            $this->general->updateRecord($this->tablename, $updateData, "$this->primarykey");                                        
            
            
            $tablename = $this->tablename;
            $imagefieldid = $id;
            $imagefieldslist = array("Picture");


            // ==================== upload image
            $inputName      = "txt_image";            
            if(isset($_FILES[$inputName]) &&  $_FILES[$inputName]['name'] != ""){                                                                                  
            $oldimagename   = "old_image_image";                                    
            $imagefolder    = "products";                                   
            $updatedfield   = "Picture";                        
            $imageWidth     = "400";
            $imageHeight    = "400";
            $thumbimageWidth     = "100";
            $thumbimageHeight    = "100";             
            $resultimage = $this->ImageProcess->imageUpload($oldimagename,$slug,$imagefolder,$imageWidth,$imageHeight,$thumbimageWidth,$thumbimageHeight,$inputName,$tablename,$updatedfield,$imagefieldslist,$imagefieldid, $this->primarykey);            
            }
            // ===================================
            
            // =========================== update dynamic fields
            foreach($data['dfields'] as $row)
            {
                $updateData2 = array(
                "PFVI" 	=> $row->PFVI,
                "Value"             => $this->input->post("txt_$row->FieldID"),                                 
                "date_modified"         => date("Y-m-d H:i:s")
                );
                $this->general->updateRecord($this->tablename2, $updateData2, "PFVI");                 
            }
            // =========================================
            
            
            $data['message'] = "Product updated successfully";
        }
            
        $data['record'] = $this->general->getRecordWhere($this->tablename,array("$this->primarykey"=>$id), "$this->primarykey","desc");    
        $data['dfields'] = $this->general->get_query_result($query);                                               
        $this->load->view(ADMINFOLDER."/editproduct",$data);
    }
        
        
    
}
