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

class TambahUmkm extends CI_Controller {

	public function __construct()
    {
        parent::__construct();
        $this->load->model("UserModel");
		$this->load->model("KategoriModel");
		$this->load->model("KelurahanModel");
		$this->load->model("UmkmModel");
		$this->load->model("JenisModel");
        $this->load->helper(array('form', 'url'));

		if($this->UserModel->isNotLogin()) {
			redirect(site_url('login'));
		} elseif(!($this->UserModel->isAdmin())) {
			redirect(site_url('dashboard'));
		} 
		
		$get = $this->input->get();
		if($get['id_user']==NULL){
			redirect(site_url('admin/dashboard'));
		}
    }

	public function index()
	{

		$get = $this->input->get();
		$pemilik = $this->UserModel->getUsersById($get['id_user']);
		
		if($this->input->post()){
			$post=$this->input->post();
			if($post['nama']!=='umkm'){
					if($this->UmkmModel->save($pemilik->id_user)){

						$current_umkm = $this->UmkmModel->getLastUmkmByIdPemilik($pemilik->id_user);
		
						if(strlen($_FILES['foto_umkm']['tmp_name'])>0){
							$config['upload_path']          = './assets/images/umkm/';
							$config['allowed_types']        = 'jpg|jpeg|gif|png';
							$config['max_size']             = 100;
							$config['max_width']            = 1024;
							$config['max_height']           = 768;
							$config['file_name']			= $current_umkm->id_umkm;
							$config['overwrite'] 			= TRUE;
					
							$this->load->library('upload', $config);
		
							if ( ! $this->upload->do_upload('foto_umkm')){
								$foto_umkm = 'umkm.png';
								$this->UmkmModel->setFirstImage($current_umkm->id_umkm,$foto_umkm);
								$data['error_upload'] = $this->upload->display_errors();
								$data['msg']="success";
							} else {
								$file = $this->upload->data();
		
								if($this->UmkmModel->setFirstImage($current_umkm->id_umkm,$file['file_name'])){
									$data['msg']="success";
								} else {
									$foto_umkm = 'umkm.png';
									$this->UmkmModel->setFirstImage($current_umkm->id_umkm,$foto_umkm);
									$data['error_upload'] = 'gagal upload foto';
									$data['msg']="success";
								}
							}
			
						} else {
									$foto_umkm = 'umkm.png';
									$this->UmkmModel->setFirstImage($current_umkm->id_umkm,$foto_umkm);
									$data['msg']="success";
						}
		
					} else {
						$data['msg']="error!";
					}
			} else {
				$data['msg']="error!";
			}
			
			
        }

			$daftarjenis = $this->JenisModel->getJenis();
			$data['daftarjenis'] = $daftarjenis;
			$data['listkelurahan'] = $this->KelurahanModel->getKelurahan();
			$data['pemilik'] = $pemilik;
			$data['user_logged'] = $this->session->userdata('user_logged');
			$this->load->view('admin/tambahumkm',$data);
		
	}

	
}