<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Logic extends AdminController {

	function __construct() {
        parent::__construct();
    }
	
	
	public function cwUpload($field_name = '', $target_folder = '', $file_name = '', $thumb = FALSE, $thumb_folder = '', $thumb_width = '', $thumb_height = ''){

		//folder path setup
		$target_path = $target_folder;
		$thumb_path = $thumb_folder;
		
		//file name setup
		$filename_err = explode(".",$_FILES[$field_name]['name']);
		$filename_err_count = count($filename_err);
		$file_ext = $filename_err[$filename_err_count-1];
		if($file_name != ''){
			$fileName = $file_name.'.'.$file_ext;
		}else{
			$fileName = $_FILES[$field_name]['name'];
		}
		
		//upload image path
		$upload_image = $target_path.basename($fileName);
		
		//upload image
		if(move_uploaded_file($_FILES[$field_name]['tmp_name'],$upload_image))
		{
			//thumbnail creation
			if($thumb == TRUE)
			{
				$thumbnail = $thumb_path.$fileName;
				list($width,$height) = getimagesize($upload_image);
				$thumb_create = imagecreatetruecolor($thumb_width,$thumb_height);
				switch($file_ext){
					case 'jpg':
						$source = imagecreatefromjpeg($upload_image);
						break;
					case 'jpeg':
						$source = imagecreatefromjpeg($upload_image);
						break;

					case 'png':
						$source = imagecreatefrompng($upload_image);
						break;
					case 'gif':
						$source = imagecreatefromgif($upload_image);
						break;
					default:
						$source = imagecreatefromjpeg($upload_image);
				}

				imagecopyresized($thumb_create,$source,0,0,0,0,$thumb_width,$thumb_height,$width,$height);
				switch($file_ext){
					case 'jpg' || 'jpeg':
						imagejpeg($thumb_create,$thumbnail,100);
						break;
					case 'png':
						imagepng($thumb_create,$thumbnail,100);
						break;

					case 'gif':
						imagegif($thumb_create,$thumbnail,100);
						break;
					default:
						imagejpeg($thumb_create,$thumbnail,100);
				}

			}

			return $fileName;
		}
		else
		{
			return false;
		}
	}
	public function resizeImage($sourceImage, $targetImage, $maxWidth, $maxHeight, $quality = 80)
	{
		// Obtain image from given source file.
		if (!$image = @imagecreatefromjpeg($sourceImage))
		{
			return false;
		}

		// Get dimensions of source image.
		list($origWidth, $origHeight) = getimagesize($sourceImage);

		if ($maxWidth == 0)
		{
			$maxWidth  = $origWidth;
		}

		if ($maxHeight == 0)
		{
			$maxHeight = $origHeight;
		}

		// Calculate ratio of desired maximum sizes and original sizes.
		$widthRatio = $maxWidth / $origWidth;
		$heightRatio = $maxHeight / $origHeight;

		// Ratio used for calculating new image dimensions.
		$ratio = min($widthRatio, $heightRatio);

		// Calculate new image dimensions.
		$newWidth  = (int)$origWidth  * $ratio;
		$newHeight = (int)$origHeight * $ratio;

		// Create final image with new dimensions.
		$newImage = imagecreatetruecolor($newWidth, $newHeight);
		imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $origWidth, $origHeight);
		imagejpeg($newImage, $targetImage, $quality);

		// Free up the memory.
		imagedestroy($image);
		imagedestroy($newImage);

		return true;
	}	

    public function upload_foto($file,$folder,$thumb=FALSE,$thumb_width){
    	$file_image = "";

    	//$upload_dir = $this->config->item('upload_path');
    	$upload_dir = "uploads/";
		
		$FILE_MIMES = array('image/jpeg','image/jpg','image/png','image/x-icon');
		$FILE_EXTS  = array('.jpeg','.jpg','.png'.'.ico');
		
		if (isset($file) && $file['name'] != "") {
			$file_type 	= $file['type']; 
			$file_image = $file['name'];
			$file_size 	= $file['size'];
			$file_ext 	= strtolower(substr($file_image,strrpos($file_image,".")));

			$temp_name 	= $file['tmp_name'];
			$file_image = str_replace("\\","",$file_image);
			$file_image = str_replace("'","",$file_image);

            $file_edit = str_replace(" ","_",$file_image);
            $random_digit=rand(0000,9999);
            $file_image = $folder.'_'.$random_digit."_".$file_edit;

			$file_path 	= $upload_dir.$folder.'/'.$file_image;

			if (!in_array($file_type, $FILE_MIMES) && !in_array($file_ext, $FILE_EXTS) ) {
				die(json_encode(array('status'=>'error', 'message' => "Sorry, $file_image($file_type) is not allowed to be uploaded")));
			}
			$result = move_uploaded_file($temp_name, $file_path);

			if ($result) {
				if($thumb==TRUE){
					$thumb_path = $upload_dir.$folder.'/thumb/';
					$thumbnail = $thumb_path.$file_image;
					$upload_image = $file_path;
					if($thumb_width==""){
						$thumb_width = 300;
					}else{
						$thumb_width = $thumb_width;
					}
					$info = getimagesize($upload_image);
					$aspectRatio = $info[1] / $info[0];
					$thumb_height = (int)($aspectRatio * $thumb_width) . "px";
					$thumb_width .= "px";  

					list($width,$height) = getimagesize($upload_image);
					$thumb_create = imagecreatetruecolor($thumb_width,$thumb_height);
					switch($file_ext){
						case '.jpg':
							$source = imagecreatefromjpeg($upload_image);
							break;
						case '.jpeg':
							$source = imagecreatefromjpeg($upload_image);
							break;

						case '.png':
							$source = imagecreatefrompng($upload_image);
							break;
						case '.gif':
							$source = imagecreatefromgif($upload_image);
							break;
						default:
							$source = imagecreatefromjpeg($upload_image);
					}
					//$source = imagecreatefrompng($upload_image);
					imagecopyresized($thumb_create,$source,0,0,0,0,$thumb_width,$thumb_height,$width,$height);
					switch($file_ext){
						case '.jpg' || '.jpeg':
							imagejpeg($thumb_create,$thumbnail,100);
							break;
						case '.png':
							imagepng($thumb_create,$thumbnail,100);
							break;

						case '.gif':
							imagegif($thumb_create,$thumbnail,100);
							break;
						default:
							imagejpeg($thumb_create,$thumbnail,100);
						break;
					}				
				}
				return $file_image;
			}
			else{
				return "";
			}
		}
    }

    public function upload_filedata($file,$folder){
		
    	$file_image = "";

    	//$upload_dir = $this->config->item('upload_data');
		$upload_dir = "uploads/";
		$FILE_MIMES = array('image/jpeg','image/jpg','image/png');
		$FILE_EXTS  = array('.jpeg','.jpg','.png');
		
		if (isset($file) && $file['name'] != "") {
			$file_type 	= $file['type']; 
			$file_image = $file['name'];
			$file_size 	= $file['size'];
			$file_ext 	= strtolower(substr($file_image,strrpos($file_image,".")));
			$temp_name 	= $file['tmp_name'];
			$file_image = str_replace("\\","",$file_image);
			$file_image = str_replace("'","",$file_image);

            $file_edit = str_replace(" ","_",$file_image);
            $random_digit=rand(0000,9999);
            $file_image = $folder.'_'.$random_digit."_".$file_edit;

			$file_path 	= $upload_dir.$folder.'/'.$file_image;

			//if (!in_array($file_type, $FILE_MIMES) && !in_array($file_ext, $FILE_EXTS) ) {
			//	die(json_encode(array('status'=>'error', 'message' => "Sorry, $file_image($file_type) is not allowed to be uploaded")));
			//}
			
			$result = move_uploaded_file($temp_name, $file_path);

			if ($result) {
				return $file_image;
			}
			else{
				return "test";
			}
		}
    }

    public function multiple_upload($multifile,$folder){
        $return = array();

        if(isset($multifile)){
            $multifile = $this->reArrayFiles($multifile);
            $a = 0;
            foreach($multifile as $file){
                $file_image = "";

                $upload_dir = $this->config->item('upload_path');
                
                $FILE_MIMES = array('image/jpeg','image/jpg','image/png');
                $FILE_EXTS  = array('.jpeg','.jpg','.png');
                
                if (isset($file) && $file['name'] != "") {
                    $file_type  = $file['type']; 
                    $file_image = $file['name'];
                    $file_size  = $file['size'];
                    $file_ext   = strtolower(substr($file_image,strrpos($file_image,".")));
                    $temp_name  = $file['tmp_name'];
                    $file_image = str_replace("\\","",$file_image);
                    $file_image = str_replace("'","",$file_image);

                    $file_edit = str_replace(" ","_",$file_image);
                    $random_digit=rand(0000,9999);
                    $file_image = $folder.'_'.$random_digit."_".$file_edit;

                    $file_path  = $upload_dir.$folder.'/'.$file_image;

                    if (!in_array($file_type, $FILE_MIMES) && !in_array($file_ext, $FILE_EXTS) ) {
                        die(json_encode(array('status'=>'error', 'message' => "Sorry, $file_image($file_type) is not allowed to be uploaded")));
                    }
                    
                    $result = move_uploaded_file($temp_name, $file_path);

                    if ($result) {
                        array_push($return, $file_image);
                    }
                }
                $a++;
            }
        }
        return $return;
    }
	public function importProses(){
		$next = false;
		if($_FILES['excel']['size'] !== 0){ 
			$values = end(explode(".", $_FILES["excel"]["name"])); 
			$format = array("xls", "xlsx", "csv");  
			if(in_array($values, $format)) {  
				if(isset($_FILES['excel'])){
				if($_FILES['excel']['tmp_name']){
				if(!$_FILES['excel']['error'])
				{

					$inputFile = $_FILES['excel']['tmp_name'];
					$extension = strtoupper(pathinfo($inputFile, PATHINFO_EXTENSION));
					//if($extension == 'xls'){

						try {
							 $inputFileType = PHPExcel_IOFactory::identify($inputFile);
							 $objReader = PHPExcel_IOFactory::createReader($inputFileType);
								 $objPHPExcel = $objReader->load($inputFile);
						} catch(Exception $e) {
								die($e->getMessage());
						}
 
						$sheet = $objPHPExcel->getSheet(0); 
						$highestRow = $sheet->getHighestRow(); 
						$highestColumn = $sheet->getHighestColumn();

						for ($row = 2; $row <= $highestRow; $row++){ 
							$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE)[0];
							$kategori = $rowData[3];
							$satuan = $rowData[5];
							$supplier = $rowData[10];
							$idkategori = $this->model_global->get_data(array('data' => 'row','table' => 'kategori', 'where' => array( 'nama' => $kategori)))['id_kategori'];
							$idsatuan = $this->model_global->get_data(array('data' => 'row','table' => 'satuan', 'where' => array( 'nama' => $satuan)))['id_satuan'];
							$idsupplier = $this->model_global->get_data(array('data' => 'row','table' => 'supplier', 'where' => array( 'nama' => $supplier)))['id_supplier'];
							$kode = $this->model_global->get_data(array('data' => 'row','table' => 'barang', 'where' => array( 'kode' => $rowData[1])));
							$data["id_satuan"] = $idsatuan;
							$data["id_supplier"] = $idsupplier;
							$data["id_kategori"] = $idkategori;
							$data["kode"] = $rowData[1];
							$data["nama"] = $rowData[2];
							$data["harga_beli"] = $rowData[6];
							$data["harga_resep"] = $rowData[7];
							$data["harga_satuan"] = $rowData[8];
							$data["harga_box"] = $rowData[9];
							$data["stok"] = $rowData[4];
							//echo $kode['id_barang']."<br>";
							if(count($kode)>0){
								//update
								//$data["status"] = 1;
								$data["modified_date"] = date('Y-m-d H:i:s');
								$this->model_global->update($data, 'barang', array('id_barang' => $kode['id_barang']));

							}else{
								//new
								$data["status"] = 1;
								$data["isi"] = 1;
								$data["tgl_masuk"] = date("Y-m-d");;
								$data["modified_date"] = '';
								$data["created_date"] = date('Y-m-d H:i:s');
								$this->model_global->insert($data, 'barang');
								$insert_id = $this->db->insert_id();
							}
						}
						//die();
						$next = true;
					/*}
					else{
						echo $extension;
						echo "Please upload an xls file";
					}*/
				}
				else{
					echo $_FILES['excel']['error'];
				}
				}
				}
			}
		}
		if($next){
			redirect($this->template['url'].'import?s=true&m=Data Berhasil Diimport');
		}
		else{
			redirect($this->template['url'].'import?s=false&m=Data Gagal Diimport');
		}	
	}
	public function barangProses(){	
        if(isset($_POST['action']) && $_POST['action'] == 'edit'){
            $id = $_POST['_id'];
            unset($_POST['action']);
            unset($_POST['_id']);
            $_POST["modified_date"] = date('Y-m-d H:i:s');

            $update = $this->model_global->update($_POST, 'barang', array('id_barang' => $id));
            if($update){
                redirect($this->template['url'].'barang-new?_id='.$id.'&s=true&m=Data Berhasil Diubah');
            }
            else{
                redirect($this->template['url'].'barang-new?_id='.$id.'&s=false&m=Data Gagal Diubah');
            }
        }
        else{
            $_POST["modified_date"] = '';
            $_POST["created_date"] = date('Y-m-d H:i:s');
            $insert_id = $this->model_global->insert($_POST, 'barang');
            if($insert_id){
                redirect($this->template['url'].'barang-new?_id='.$id.'&s=true&m=Data Berhasil Disimpan');
            }
            else{
                redirect($this->template['url'].'barang-new?_id='.$id.'&s=false&m=Data Gagal Disimpan');
            }
        }
    }	
	
	public function transaksiProses(){	 
		$ada = 0;
		foreach($_POST['item'] as $key => $value){
			$ada = count($value);
		}
		if($ada==0){
			$data['status'] = "false";
		}else{
			$head["modified_date"] = '';
			$head["created_date"] = date('Y-m-d H:i:s');
			$head['keterangan'] = $_POST['keterangan'];
			$head['no'] = $_POST['no'];
			$head['pelanggan'] = $_POST['pelanggan'];
			$head['total'] = $_POST['subtotal'];
			$head['diskon'] = $_POST['diskon'];
			$head['potongan'] = $_POST['potongan'];
			$head['bayar'] = $_POST['bayar'];
			$head['sisa'] = $_POST['sisa'];
			$head['grand_total'] = $_POST['grand_total'];
			$head['status'] = '1';
	 
			$data['status'] = "false";
			$insert_id = $this->model_global->insert($head, 'transaksi');
			if($insert_id){
				$ids = $this->db->insert_id();
				for($a=0; $a<$ada; $a++){
					$items["modified_date"] = '';
					$items["created_date"] = date('Y-m-d H:i:s');
					$items['id_transaksi'] = $ids;
					$items['id_barang'] = $_POST['item']['id_barang'][$a];
					$items['qty'] = $_POST['item']['qty'][$a];
					$items['jenis_harga'] = $_POST['item']['jenis_harga'][$a];
					$items['harga'] = $_POST['item']['harga'][$a];
					$items['total'] = $_POST['item']['total'][$a];
					$items['status'] = '1';
					$barang = $this->model_global->get_data(array('data' => 'row','table' => 'barang', 'where' => array('id_barang' => $items['id_barang'])));
					$items['harga_beli'] = $barang['harga_beli'];
					$insert_id = $this->model_global->insert($items, 'item');
					$up['stok'] = $barang['stok'] - $items['qty'];
					$this->model_global->update($up, 'barang', array('id_barang' => $items['id_barang']));
				}
				$data['status'] = "true";
				$data['id'] = $ids;
			}
			else{
				$data['status'] = "false";
			}
		}
		echo json_encode($data);
    }	
	public function pembelianProses(){	 
		$ada = 0;
		foreach($_POST['item'] as $key => $value){
			$ada = count($value);
		}
		
		$head["modified_date"] = '';
		$head["created_date"] = date('Y-m-d H:i:s');
		$head['keterangan'] = $_POST['keterangan'];
		$head['no'] = $_POST['no'];
		$head['id_supplier'] = $_POST['id_supplier'];
		$head['total'] = $_POST['subtotal'];
		$head['tanggal'] = $_POST['tanggal'];
		$head['jatuh_tempo'] = $_POST['jatuh_tempo'];
		$head['status'] = '1';
 
		$data['status'] = "false";
		$insert_id = $this->model_global->insert($head, 'pembelian');
		if($insert_id){
			$ids = $this->db->insert_id();
			for($a=0; $a<$ada; $a++){
				$items["modified_date"] = '';
				$items["created_date"] = date('Y-m-d H:i:s');
				$items['id_pembelian'] = $ids;
				$items['id_barang'] = $_POST['item']['id_barang'][$a];
				$items['qty'] = $_POST['item']['qty'][$a];
				$items['harga'] = $_POST['item']['harga'][$a];
				$items['total'] = $_POST['item']['total'][$a];
				$items['status'] = '1';
				$items['tanggal'] = $_POST['tanggal'];
				$items['jatuh_tempo'] = $_POST['jatuh_tempo'];
				$barang = $this->model_global->get_data(array('data' => 'row','table' => 'barang', 'where' => array('id_barang' => $items['id_barang'])));
				$up['stok'] = $barang['stok'] + $items['qty'];
				$items['harga_awal'] = $barang['harga_beli'];
				$avg = (($barang['harga_beli'] * $barang['stok']) + ($items['harga'] * $items['qty'])) / $up['stok'];
				$items['avg'] = $avg;
				$insert_id = $this->model_global->insert($items, 'beli');
				$up['harga_beli'] = $avg;
				$this->model_global->update($up, 'barang', array('id_barang' => $items['id_barang']));
			}
			$data['status'] = "true";
			$data['id'] = $ids;
		}
		else{
			$data['status'] = "false";
		}
		echo json_encode($data);
    }
	public function mutasiProses(){	 
		$ada = 0;
		foreach($_POST['item'] as $key => $value){
			$ada = count($value);
		}
		if($_POST['tanggal']==""){
			$_POST['tanggal'] = date("Y-m-d");
		}
		$head["modified_date"] = '';
		$head["created_date"] = date('Y-m-d H:i:s');
		$head['keterangan'] = $_POST['keterangan'];
		$head['tujuan'] = $_POST['tujuan'];
		$head['no'] = $_POST['no']; 
		$head['total'] = $_POST['subtotal'];
		$head['tanggal'] = $_POST['tanggal']; 
		$head['status'] = '1';
 
		$data['status'] = "false";
		$insert_id = $this->model_global->insert($head, 'mutasi');
		if($insert_id){
			$ids = $this->db->insert_id();
			for($a=0; $a<$ada; $a++){
				$items["modified_date"] = '';
				$items["created_date"] = date('Y-m-d H:i:s');
				$items['id_mutasi'] = $ids;
				$items['tanggal'] = $_POST['tanggal'];
				$items['id_barang'] = $_POST['item']['id_barang'][$a];
				$items['qty'] = $_POST['item']['qty'][$a];
				$items['harga'] = $_POST['item']['harga'][$a];
				$items['total'] = $_POST['item']['total'][$a];
				$items['status'] = '1';  
				$barang = $this->model_global->get_data(array('data' => 'row','table' => 'barang', 'where' => array('id_barang' => $items['id_barang'])));
				$up['stok'] = $barang['stok'] - $items['qty'];
				$insert_id = $this->model_global->insert($items, 'mutasi_item');
				$this->model_global->update($up, 'barang', array('id_barang' => $items['id_barang']));
			}
			$data['status'] = "true";
			$data['id'] = $ids;
		}
		else{
			$data['status'] = "false";
		}
		echo json_encode($data);
    }	
	public function supplierProses(){	
        if(isset($_POST['action']) && $_POST['action'] == 'edit'){
            $id = $_POST['_id'];
            unset($_POST['action']);
            unset($_POST['_id']);
            $_POST["modified_date"] = date('Y-m-d H:i:s');

            $update = $this->model_global->update($_POST, 'supplier', array('id_supplier' => $id));
            if($update){
                redirect($this->template['url'].'supplier-new?_id='.$id.'&s=true&m=Data Berhasil Diubah');
            }
            else{
                redirect($this->template['url'].'supplier-new?_id='.$id.'&s=false&m=Data Gagal Diubah');
            }
        }
        else{
            $_POST["modified_date"] = '';
            $_POST["created_date"] = date('Y-m-d H:i:s');
            $insert_id = $this->model_global->insert($_POST, 'supplier');
            if($insert_id){
                redirect($this->template['url'].'supplier-new?_id='.$id.'&s=true&m=Data Berhasil Disimpan');
            }
            else{
                redirect($this->template['url'].'supplier-new?_id='.$id.'&s=false&m=Data Gagal Disimpan');
            }
        }
    }	
	
	public function kategoriProses(){	
        if(isset($_POST['action']) && $_POST['action'] == 'edit'){
            $id = $_POST['_id'];
            unset($_POST['action']);
            unset($_POST['_id']);
            $_POST["modified_date"] = date('Y-m-d H:i:s');

            $update = $this->model_global->update($_POST, 'kategori', array('id_kategori' => $id));
            if($update){
                redirect($this->template['url'].'kategori-new?_id='.$id.'&s=true&m=Data Berhasil Diubah');
            }
            else{
                redirect($this->template['url'].'kategori-new?_id='.$id.'&s=false&m=Data Gagal Diubah');
            }
        }
        else{
            $_POST["modified_date"] = '';
            $_POST["created_date"] = date('Y-m-d H:i:s');
            $insert_id = $this->model_global->insert($_POST, 'kategori');
            if($insert_id){
                redirect($this->template['url'].'kategori-new?_id='.$id.'&s=true&m=Data Berhasil Disimpan');
            }
            else{
                redirect($this->template['url'].'kategori-new?_id='.$id.'&s=false&m=Data Gagal Disimpan');
            }
        }
    }	
	public function satuanProses(){	
        if(isset($_POST['action']) && $_POST['action'] == 'edit'){
            $id = $_POST['_id'];
            unset($_POST['action']);
            unset($_POST['_id']);
            $_POST["modified_date"] = date('Y-m-d H:i:s');

            $update = $this->model_global->update($_POST, 'satuan', array('id_satuan' => $id));
            if($update){
                redirect($this->template['url'].'satuan-new?_id='.$id.'&s=true&m=Data Berhasil Diubah');
            }
            else{
                redirect($this->template['url'].'satuan-new?_id='.$id.'&s=false&m=Data Gagal Diubah');
            }
        }
        else{
            $_POST["modified_date"] = '';
            $_POST["created_date"] = date('Y-m-d H:i:s');
            $insert_id = $this->model_global->insert($_POST, 'satuan');
            if($insert_id){
                redirect($this->template['url'].'satuan-new?_id='.$id.'&s=true&m=Data Berhasil Disimpan');
            }
            else{
                redirect($this->template['url'].'satuan-new?_id='.$id.'&s=false&m=Data Gagal Disimpan');
            }
        }
    }	
	
	public function strukProses(){ 
		$update = $this->model_global->update($_POST, 'website', array('id_website' => 1));
		if($update){
			redirect($this->template['url'].'struk');
		}
		else{
			redirect(base_url());
		} 
    }	
	
	public function slideProses(){
		$cb = $_GET['cb'];
        if(isset($_POST['action']) && $_POST['action'] == 'edit'){
            $id = $_POST['_id'];
            unset($_POST['action']);
            unset($_POST['_id']);
			
			if(empty($_FILES['image']['name'])){
				unset($_POST['image']);
			}else{
				unlink("uploads/slide/".$_POST['img_awal']);
				$_POST['image'] = $this->upload_foto($_FILES['image'],"slide",TRUE);
			}
			unset($_POST['img_awal']);
            $_POST["modified_date"] = date('Y-m-d H:i:s');

            $update = $this->model_global->update($_POST, 'slide', array('id_slide' => $id));
            if($update){
                redirect($this->template['url'].'slide-new?_id='.$id.'&s=true&m=Data Berhasil Diubah');
            }
            else{
                redirect($this->template['url'].'slide-new?_id='.$id.'&s=false&m=Data Gagal Diubah');
            }
        }
        else{
			unset($_POST['img_awal']); 
            $_POST["modified_date"] = '';
            $_POST["created_date"] = date('Y-m-d H:i:s');

			if(empty($_FILES['image']['name'])){
				unset($_POST['image']);
			}else{
				$_POST['image'] = $this->upload_foto($_FILES['image'],"slide",TRUE);
			} 
            $insert_id = $this->model_global->insert($_POST, 'slide');
            if($insert_id){
                redirect($this->template['url'].'slide-new?_id='.$id.'&s=true&m=Data Berhasil Disimpan');
            }
            else{
                redirect($this->template['url'].'slide-new?_id='.$id.'&s=false&m=Data Gagal Disimpan');
            }
        }
    }
	public function aboutProses(){ 
        if(isset($_POST['action']) && $_POST['action'] == 'edit'){
            $id = $_POST['_id'];
            unset($_POST['action']);
            unset($_POST['_id']);

            $update = $this->model_global->update($_POST, 'about', array('id_about' => $id));
            if($update){
                redirect($this->template['url'].'about-new?_id='.$id.'&s=true&m=Data Berhasil Diubah');
            }
            else{
                redirect($this->template['url'].'about-new?_id='.$id.'&s=false&m=Data Gagal Diubah');
            }
        }
        else{ 
            $insert_id = $this->model_global->insert($_POST, 'about');
            if($insert_id){
                redirect($this->template['url'].'about-new?_id='.$id.'&s=true&m=Data Berhasil Disimpan');
            }
            else{
                redirect($this->template['url'].'about-new?_id='.$id.'&s=false&m=Data Gagal Disimpan');
            }
        }
    }
	public function howProses(){ 
        if(isset($_POST['action']) && $_POST['action'] == 'edit'){
            $id = $_POST['_id'];
            unset($_POST['action']);
            unset($_POST['_id']);

            $update = $this->model_global->update($_POST, 'how', array('id_how' => $id));
            if($update){
                redirect($this->template['url'].'how-new?_id='.$id.'&s=true&m=Data Berhasil Diubah');
            }
            else{
                redirect($this->template['url'].'how-new?_id='.$id.'&s=false&m=Data Gagal Diubah');
            }
        }
        else{ 
            $insert_id = $this->model_global->insert($_POST, 'how');
            if($insert_id){
                redirect($this->template['url'].'how-new?_id='.$id.'&s=true&m=Data Berhasil Disimpan');
            }
            else{
                redirect($this->template['url'].'how-new?_id='.$id.'&s=false&m=Data Gagal Disimpan');
            }
        }
    }
	public function servicesProses(){ 
        if(isset($_POST['action']) && $_POST['action'] == 'edit'){
            $id = $_POST['_id'];
            unset($_POST['action']);
            unset($_POST['_id']);

            $update = $this->model_global->update($_POST, 'services', array('id_services' => $id));
            if($update){
                redirect($this->template['url'].'services-new?_id='.$id.'&s=true&m=Data Berhasil Diubah');
            }
            else{
                redirect($this->template['url'].'services-new?_id='.$id.'&s=false&m=Data Gagal Diubah');
            }
        }
        else{ 
            $insert_id = $this->model_global->insert($_POST, 'services');
            if($insert_id){
                redirect($this->template['url'].'services-new?_id='.$id.'&s=true&m=Data Berhasil Disimpan');
            }
            else{
                redirect($this->template['url'].'services-new?_id='.$id.'&s=false&m=Data Gagal Disimpan');
            }
        }
    }
	public function workProses(){ 
        if(isset($_POST['action']) && $_POST['action'] == 'edit'){
            $id = $_POST['_id'];
            unset($_POST['action']);
            unset($_POST['_id']);
			if(empty($_FILES['media_photo']['name'])){
				unset($_POST['media_photo']);
			}else{
				unlink("uploads/slide/".$_POST['img_awal']);
				$_POST['media_photo'] = $this->upload_foto($_FILES['media_photo'],"slide",TRUE);
			}
			unset($_POST['img_awal']);
            $update = $this->model_global->update($_POST, 'work', array('id_work' => $id));
            if($update){
                redirect($this->template['url'].'work-new?_id='.$id.'&s=true&m=Data Berhasil Diubah');
            }
            else{
                redirect($this->template['url'].'work-new?_id='.$id.'&s=false&m=Data Gagal Diubah');
            }
        }
        else{ 
			unset($_POST['img_awal']); 
			if(empty($_FILES['media_photo']['name'])){
				unset($_POST['media_photo']);
			}else{
				$_POST['media_photo'] = $this->upload_foto($_FILES['media_photo'],"work",TRUE);
			} 
			
            $insert_id = $this->model_global->insert($_POST, 'work');
            if($insert_id){
                redirect($this->template['url'].'work-new?_id='.$id.'&s=true&m=Data Berhasil Disimpan');
            }
            else{
                redirect($this->template['url'].'work-new?_id='.$id.'&s=false&m=Data Gagal Disimpan');
            }
        }
    }
	public function processProses(){ 
        if(isset($_POST['action']) && $_POST['action'] == 'edit'){
            $id = $_POST['_id'];
            unset($_POST['action']);
            unset($_POST['_id']);
			if(empty($_FILES['media_photo']['name'])){
				unset($_POST['media_photo']);
			}else{
				unlink("uploads/slide/".$_POST['img_awal']);
				$_POST['media_photo'] = $this->upload_foto($_FILES['media_photo'],"slide",TRUE);
			}
			unset($_POST['img_awal']);
            $update = $this->model_global->update($_POST, 'process', array('id_process' => $id));
            if($update){
                redirect($this->template['url'].'process-new?_id='.$id.'&s=true&m=Data Berhasil Diubah');
            }
            else{
                redirect($this->template['url'].'process-new?_id='.$id.'&s=false&m=Data Gagal Diubah');
            }
        }
        else{ 
			unset($_POST['img_awal']); 
			if(empty($_FILES['media_photo']['name'])){
				unset($_POST['media_photo']);
			}else{
				$_POST['media_photo'] = $this->upload_foto($_FILES['media_photo'],"process",TRUE);
			} 
			
            $insert_id = $this->model_global->insert($_POST, 'process');
            if($insert_id){
                redirect($this->template['url'].'process-new?_id='.$id.'&s=true&m=Data Berhasil Disimpan');
            }
            else{
                redirect($this->template['url'].'process-new?_id='.$id.'&s=false&m=Data Gagal Disimpan');
            }
        }
    }
	public function invoiceProses(){ 
        if(isset($_POST['action']) && $_POST['action'] == 'edit'){
            $id = $_POST['_id'];
            unset($_POST['action']);
            unset($_POST['_id']);

            $update = $this->model_global->update($_POST, 'invoice', array('id_invoice' => $id));
            if($update){
                redirect($this->template['url'].'invoice-new?_id='.$id.'&s=true&m=Data Berhasil Diubah');
            }
            else{
                redirect($this->template['url'].'invoice-new?_id='.$id.'&s=false&m=Data Gagal Diubah');
            }
        }
        else{ 
            $tiket['deskripsi'] = $_POST['deskripsi'];
            $tiket['harga'] = $_POST['harga'];
            $tiket['qty'] = $_POST['qty'];
            $tiket['total'] = $_POST['total'];
            unset($_POST['deskripsi']);
            unset($_POST['harga']);
            unset($_POST['qty']);
            unset($_POST['total']);
			
			$_POST["created_date"] = date('Y-m-d H:i:s');
			$_POST['status'] = "1";
			$_POST['status_lunas'] = "0";
            $insert_id = $this->model_global->insert($_POST, 'invoice');
            if($insert_id){
				$tiket['id_invoice'] = $this->db->insert_id();
				$tiket['tanggal'] = $_POST['tanggal'];
				$tiket['status'] = "1";
				$tiket["created_date"] = date('Y-m-d H:i:s');
				$this->model_global->insert($tiket, 'additional');
				
                redirect($this->template['url'].'invoice-new?_id='.$id.'&s=true&m=Data Berhasil Disimpan');
            }
            else{
                redirect($this->template['url'].'invoice-new?_id='.$id.'&s=false&m=Data Gagal Disimpan');
            }
        }
    }

	public function beliProses(){ 
        if(isset($_POST['action']) && $_POST['action'] == 'edit'){
            $id = $_POST['_id'];
            unset($_POST['action']);
            unset($_POST['_id']);
            unset($_POST['qty']);

            $update = $this->model_global->update($_POST, 'additional', array('id_additional' => $id));
            if($update){
                redirect($this->template['url'].'beli-new?_id='.$_POST['id_invoice'].'&additional='.$id.'&s=true&m=Data Berhasil Diubah');
            }
            else{
                redirect($this->template['url'].'beli-new?_id='.$_POST['id_invoice'].'&additional='.$id.'&s=false&m=Data Gagal Diubah');
            }
        }
    }
	public function additionalProses(){ 
        if(isset($_POST['action']) && $_POST['action'] == 'edit'){
            $id = $_POST['_id'];
            unset($_POST['action']);
            unset($_POST['_id']);

            $update = $this->model_global->update($_POST, 'additional', array('id_additional' => $id));
            if($update){
				$this->ceklunas($_POST['id_invoice']);
                redirect($this->template['url'].'invoice-tiket?_id='.$_POST['id_invoice'].'&additional='.$id.'&s=true&m=Data Berhasil Diubah');
            }
            else{
                redirect($this->template['url'].'invoice-tiket?_id='.$_POST['id_invoice'].'&additional='.$id.'&s=false&m=Data Gagal Diubah');
            }
        }
        else{ 
			$_POST["created_date"] = date('Y-m-d H:i:s');
			$_POST['status'] = "1";
            $insert_id = $this->model_global->insert($_POST, 'additional');
            if($insert_id){
				$this->ceklunas($_POST['id_invoice']);
                redirect($this->template['url'].'invoice-tiket?_id='.$_POST['id_invoice'].'&s=true&m=Data Berhasil Disimpan');
            }
            else{
                redirect($this->template['url'].'invoice-tiket?_id='.$_POST['id_invoice'].'&s=false&m=Data Gagal Disimpan');
            }
        }
    }
	public function bayarProses(){ 
        if(isset($_POST['action']) && $_POST['action'] == 'edit'){
            $id = $_POST['_id'];
            unset($_POST['action']);
            unset($_POST['_id']);

            $update = $this->model_global->update($_POST, 'bayar', array('id_bayar' => $id));
            if($update){
				$this->ceklunas($_POST['id_invoice']);
                redirect($this->template['url'].'invoice-bayar?_id='.$_POST['id_invoice'].'&bayar='.$id.'&s=true&m=Data Berhasil Diubah');
            }
            else{
                redirect($this->template['url'].'invoice-bayar?_id='.$_POST['id_invoice'].'&bayar='.$id.'&s=false&m=Data Gagal Diubah');
            }
        }
        else{ 
			$_POST["created_date"] = date('Y-m-d H:i:s');
			$_POST['status'] = "1";
            $insert_id = $this->model_global->insert($_POST, 'bayar');
            if($insert_id){
				$this->ceklunas($_POST['id_invoice']);
                redirect($this->template['url'].'invoice-bayar?_id='.$_POST['id_invoice'].'&s=true&m=Data Berhasil Disimpan');
            }
            else{
                redirect($this->template['url'].'invoice-bayar?_id='.$_POST['id_invoice'].'&s=false&m=Data Gagal Disimpan');
            }
        }
    }
	
	function ceklunas($invoice){
		$q = "SELECT sum(total) totala FROM `additional` where id_invoice='".$invoice."' and status='1'";
		$ccp = $this->db->query($q)->result_array();
		$total = "0";
		if(count($ccp)>0){
			$total= $ccp[0]['totala'];
		}	
		$bayar = "0";
		$q2 = "SELECT sum(total) bayar FROM `bayar` where id_invoice='".$invoice."' and status='1'";
		$ccp2 = $this->db->query($q2)->result_array();
		if(count($ccp2)>0){
			$bayar= $ccp2[0]['bayar'];
		}
		if($total==$bayar){
			$st['status_lunas'] = "1";
			$this->model_global->update($st, 'invoice', array('id_invoice' => $invoice));
		}else{
			$st['status_lunas'] = "0";
			$this->model_global->update($st, 'invoice', array('id_invoice' => $invoice));
		}
	}
	public function userProses(){
		if(isset($_POST['password'])){
			$_POST['password'] = md5($_POST['password']);
		}else{
			unset($_POST['password']);
		}
        if(isset($_POST['action']) && $_POST['action'] == 'edit'){
            $id = $_POST['_id'];
            unset($_POST['action']);
            unset($_POST['_id']); 
            $_POST["modified_date"] = date('Y-m-d H:i:s'); 		
            $update = $this->model_global->update($_POST, 'user', array('id_user' => $id));
			
            if($update){
				redirect($this->template['url'].'user-new?_id='.$id.'&s=true&m=Data Berhasil Diubah');
            }
            else{
                redirect($this->template['url'].'user-new?_id='.$id.'&s=false&m=Data Gagal Diubah');
            }
        }
        else{
            $_POST["modified_date"] = '';
            $_POST["created_date"] = date('Y-m-d H:i:s');
			$_POST['status']='1'; 
            $insert_id = $this->model_global->insert($_POST, 'user');
            if($insert_id){
                redirect($this->template['url'].'user-new?_id='.$id.'&s=true&m=Data Berhasil Disimpan');
            }
            else{
                redirect($this->template['url'].'user-new?_id='.$id.'&s=false&m=Data Gagal Disimpan');
            }
        }
    }	
	public function sloganbannerProses(){ 
        if(isset($_POST['action']) && $_POST['action'] == 'edit'){
            $id = $_POST['_id'];
            unset($_POST['action']);
            unset($_POST['_id']);

            $update = $this->model_global->update($_POST, 'sloganbanner', array('id_sloganbanner' => $id));
            if($update){
                redirect($this->template['url'].'sloganbanner-new?_id='.$id.'&s=true&m=Data Berhasil Diubah');
            }
            else{
                redirect($this->template['url'].'sloganbanner-new?_id='.$id.'&s=false&m=Data Gagal Diubah');
            }
        }
        else{ 
            $insert_id = $this->model_global->insert($_POST, 'sloganbanner');
            if($insert_id){
                redirect($this->template['url'].'sloganbanner-new?_id='.$id.'&s=true&m=Data Berhasil Disimpan');
            }
            else{
                redirect($this->template['url'].'sloganbanner-new?_id='.$id.'&s=false&m=Data Gagal Disimpan');
            }
        }
    }


	public function upslug($table){
		$data = $this->model_global->get_data(array('select' => '*', 'table' => $table));
		if(isset($data) && count($data) > 0): foreach($data as $row):
			$field = strtolower(trim($row['nama']));
			$slugs = str_replace(" ","-",$field);
			$lat['slug'] = $slugs;
			$this->model_global->update($lat, $table,array('id_'.$table => $row['id_'.$table]));
			
		endforeach; endif; 
	}
	
    public function deletep($table,$id){
		$i = $this->model_global->get_data(array('select' => '*', 'table' => 'beli','where' => array('status' => 1,'id_pembelian'=>$id)));
		foreach($i as $row){
			$barang = $this->model_global->get_data(array('data' => 'row','table' => 'barang', 'where' => array('id_barang' => $row['id_barang'])));
			$up['stok'] = $barang['stok'] - $row['qty'];
			$up['harga_beli'] = $row['harga_awal'];
			$this->model_global->update($up, 'barang', array('id_barang' => $row['id_barang']));

			$this->model_global->delete('beli', array('id_beli' => $row['id_beli']));
		}
		
    	$delete = $this->model_global->delete($table, array('id_'.$table => $id));
        
    	if($delete){ 
			if(isset($_GET['_id'])){
				redirect($this->template['url'].$_GET['part']."?_id=".$_GET['_id']);
			}else{
				redirect($this->template['url'].$_GET['part']);
			}
    	}
    	else{
    		redirect(base_url());
    	}
    }
    public function deletem($table,$id){
		$i = $this->model_global->get_data(array('select' => '*', 'table' => 'mutasi_item','where' => array('status' => 1,'id_mutasi'=>$id)));
		foreach($i as $row){
			$barang = $this->model_global->get_data(array('data' => 'row','table' => 'barang', 'where' => array('id_barang' => $row['id_barang'])));
			$up['stok'] = $barang['stok'] + $row['qty'];
			$this->model_global->update($up, 'barang', array('id_barang' => $row['id_barang']));

			$this->model_global->delete('mutasi_item', array('id_mutasi' => $row['id_mutasi']));
		}
		
    	$delete = $this->model_global->delete($table, array('id_'.$table => $id));
        
    	if($delete){ 
			if(isset($_GET['_id'])){
				redirect($this->template['url'].$_GET['part']."?_id=".$_GET['_id']);
			}else{
				redirect($this->template['url'].$_GET['part']);
			}
    	}
    	else{
    		redirect(base_url());
    	}
    }
    public function deletet($table,$id){
		$i = $this->model_global->get_data(array('select' => '*', 'table' => 'item','where' => array('status' => 1,'id_transaksi'=>$id)));
		foreach($i as $row){
			$barang = $this->model_global->get_data(array('data' => 'row','table' => 'barang', 'where' => array('id_barang' => $row['id_barang'])));
			$up['stok'] = $barang['stok'] + $row['qty'];
			$this->model_global->update($up, 'barang', array('id_barang' => $row['id_barang']));

			$this->model_global->delete('item', array('id_item' => $row['id_item']));
		}
		
    	$delete = $this->model_global->delete($table, array('id_'.$table => $id));
        
    	if($delete){ 
			if(isset($_GET['_id'])){
				redirect($this->template['url'].$_GET['part']."?_id=".$_GET['_id']);
			}else{
				redirect($this->template['url'].$_GET['part']);
			}
    	}
    	else{
    		redirect(base_url());
    	}
    }
    public function delete($table,$id){
    	$delete = $this->model_global->delete($table, array('id_'.$table => $id));
        
    	if($delete){ 
			if(isset($_GET['_id'])){
				redirect($this->template['url'].$_GET['part']."?_id=".$_GET['_id']);
			}else{
				redirect($this->template['url'].$_GET['part']);
			}
    	}
    	else{
    		redirect(base_url());
    	}
    }
 
    public function setlatest($id,$part){
		$up['latest'] = "0";
		$this->model_global->update($up, "video", array('latest' => '1'));
		$up['latest'] = "1";
		$this->model_global->update($up, "video", array('id_video' => $id));
		redirect($this->template['url'].$part);		
	}
    public function delete_ajax($table,$id){
		$res["status_ajx"] = "true";
		$res["hasil"] = "-----";
		$gd = $this->model_global->get_data(array('data' => 'row','table' => "".$table,  'where' => array('id_'.$table => $id)));
		switch($gd['status']){
			case "1";
				$up['status']="0";
				$this->model_global->update($up, "".$table, array('id_'.$table => $id));
				$res["hasil"] = "Tidak Aktif";
			break;
			case "0";
				$up['status']="1";
				$this->model_global->update($up, "".$table, array('id_'.$table => $id));
				$res["hasil"] = "Aktif";
			break;
		}
		$res["seta"] = $up['status'];
		
		echo json_encode($res);
    }

    public function validate_slug($table, $column, $slug, $id = 0) {
        if ($id != 0)
            $this->cimongo->where_ne('_id', new MongoId($id));

        $this->cimongo->like($column, $slug);
        
        $this->cimongo->order_by(array($column => 'desc'));
        $this->cimongo->limit(1);
        $res = $this->cimongo->get($table);
        if ($res->num_rows() == 0) {
            return $slug;
        } else {
            $row = $res->row_array();
            $slug = $row[$column];
            preg_match('/^(.+)([0-9]+)$/', $slug, $found);
            if (empty($found)) {
                return $slug.'-1';
            } else {
                return $slug.'-'.((int)$found+1);
            }
        }
    }
	
}