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

class EditPemilik extends CI_Controller {

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

		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()){
		
			if(strlen($_FILES['foto_user']['tmp_name'])>0){
				$config['upload_path']          = './assets/images/';
				$config['allowed_types']        = 'jpg|jpeg|gif|png';
				$config['max_size']             = 100;
				$config['max_width']            = 1024;
				$config['max_height']           = 768;
				$config['file_name']			= $pemilik->username;
				$config['overwrite'] 			= TRUE;
		
				$this->load->library('upload', $config);

				if ( ! $this->upload->do_upload('foto_user')){
					$data['error_upload'] = $this->upload->display_errors();
				}else{
					$foto_lama = $pemilik->foto_user;
					$file = $this->upload->data();
					if($this->UserModel->update($pemilik->id_user,$file['file_name'])){
						if($pemilik->foto_user!=='user.png'){
							unlink('./assets/images/'.$foto_lama);
						}
						redirect(site_url('admin/editpemilik?id_user='.$pemilik->id_user.'&msg=success'));
					} else {
						$data['msg']="error!";
					}
				}
			} else {
				$foto_user = $pemilik->foto_user;
				if($this->UserModel->update($pemilik->id_user,$foto_user)){
					redirect(site_url('admin/editpemilik?id_user='.$pemilik->id_user.'&msg=success'));
				} else {
					$data['msg']="error!";
				}
			}
        	
        }


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

	
}
