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

class EditUmkm extends CI_Controller {

	public function __construct()
    {
		
        parent::__construct();
        $this->load->model("UserModel");
		$this->load->model("UmkmModel");
		$this->load->model("KategoriModel");
		$this->load->model("KelurahanModel");
		$this->load->model("JenisModel");

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

	public function index()
	{

		$get = $this->input->get();
		$umkm = $this->UmkmModel->getUmkmsById($get['id_umkm']);
		

		if($this->input->post()){

			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']			= $umkm->id_umkm;
				$config['overwrite'] 			= TRUE;
		
				$this->load->library('upload', $config);

				if ( ! $this->upload->do_upload('foto_umkm')){
					$data['error_upload'] = $this->upload->display_errors();
				} else {
					$foto_lama = $umkm->foto_umkm;
					$file = $this->upload->data();
					if($this->UmkmModel->update($umkm->id_umkm,$file['file_name'])){
						if($umkm->foto_umkm!=='umkm.png'){
							unlink('./assets/images/umkm/'.$foto_lama);
						}
						redirect(site_url('admin/editumkm?id_umkm='.$umkm->id_umkm.'&msg=success'));
					} else {
						$data['msg']="error!";
					}
				}

			} else{
				$foto_umkm = $umkm->foto_umkm;
				if($this->UmkmModel->update($umkm->id_umkm,$foto_umkm)){
					redirect(site_url('admin/editumkm?id_umkm='.$umkm->id_umkm.'&msg=success'));
				} else {
					$data['msg']="error!";
				}
			}
        }

		$daftarjenis = $this->JenisModel->getJenis();
		$data['daftarjenis'] = $daftarjenis;
		$data['listkelurahan'] = $this->KelurahanModel->getKelurahan();
		$data['umkm'] = $umkm;
		$data['user_logged'] = $this->session->userdata('user_logged');

		$this->load->view('admin/editumkm',$data);
		
	}

	
}
