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

class Klcab extends CI_Controller
{

	function __construct()
	{
		parent::__construct();
		check_not_login(); // kode akses login diambil dari helper
		check_admin();
		$this->load->model(['Lokcab_m', 'Invid_m']);
		$this->load->library('form_validation');
	}

	public function index()
	{
		$data['lokcabID'] = $this->Lokcab_m->get();
		$data['invid'] = $this->Invid_m->get();
		$this->template->load('template', 'klcab', $data);
	}

	public function addinv()
	{
		$this->form_validation->set_rules('invkm_alamat', 'invkm_alamat', 'trim|required|is_unique[tb_invkm.invkm_alamat]');

		if ($this->form_validation->run() == False) {
			$data['lokcabID'] = $this->Lokcab_m->get();
			$data['invid'] = $this->Invid_m->get();

			$this->template->load('template', 'invid', $data);
		} else {
			$post = $this->input->post(null, TRUE);
			$config['upload_path']          = './upload/foto/invkm/';
			$config['allowed_types']        = 'gif|jpg|png|jpeg';
			$config['max_size']             = 2048; // 2mb
			$config['file_name']            = 'KM-' . date('ymd') . '-' . substr(md5(rand()), 0, 2);
			$this->load->library('upload', $config);
			if (!$this->upload->do_upload('invkm_foto')) {
				$post['invkm_foto'] = 'kimo.jpg';
				$this->Invid_m->addinv($post);
				if ($this->db->affected_rows() > 0) {
					$this->session->set_flashdata('success', 'Data Investor Baru berhasil di Tambahkan');
				}
				redirect($_SERVER['HTTP_REFERER']);
			} else {
				$post['invkm_foto'] = $this->upload->data('file_name');
				$this->Invid_m->addinv($post);
				if ($this->db->affected_rows() > 0) {
					$this->session->set_flashdata('success', 'Data Investor Baru Berhasil Disimpan');
				}
				redirect($_SERVER['HTTP_REFERER']);
			}
		}
	}

	public function delinvkm($id)
	{
		$item = $this->Invid_m->get($id)->row();
		if ($item->invkm_foto != null) {
			$target_file = './upload/foto/invkm/' . $item->invkm_foto;
			unlink($target_file);
		}

		$this->Invid_m->delinvkm($id);
		if ($this->db->affected_rows() > 0) {
			$this->session->set_flashdata('success', 'Data Investor berhasil Dihapus');
		}
		redirect($_SERVER['HTTP_REFERER']);
	}
}
