<?php namespace App\Controllers\Admin;

class Country extends AdminController
{
	private $mObj;
	
	public function __construct(){		
        $this->mObj = model('App\Models\Admin\CountryModel');
		$this->menu_id = 25;
    }
	
	public function index(){
		$this->allowed('is_list');
		$data['footer_includes'] = ['country_list_js'];		
		echo $this->view_inner_template('country_list',$data);
	}
	
	public function ajax_list(){
		$this->allowed('is_list');
		$result = $this->mObj->get_datatable();
		$output = array(
			"meta" => $result['meta'],
            "data" => $result['data']
        );
        
        // Output to JSON format
        echo json_encode($output);
	}
	
	public function add(){
		$this->allowed('is_add');
	    file_put_contents(WRITEPATH.'uploads/test.txt', 'testing');
		$data['form_heading'] = "Add Country";
		
		if($this->request->getMethod() === 'post'){
			$rules = $this->get_validation_rules();
			if ($this->validate($rules)) { 
				$data_in = $this->get_column_values();				
				$this->mObj->insert($data_in);
				$this->notify_success('Record Added Successfully');
				return redirect()->to(get_admin_path('country'));
			}
		}
		$data['footer_includes'] = ['country_add_edit_js'];	
		echo $this->view_inner_template('country_add_edit',$data);
	}
	
	public function edit($country_id){
		$this->allowed('is_edit');
		$data['form_heading'] = "Edit country thumbnail";
		if($this->request->getMethod() === 'post'){
			$rules = $this->get_validation_rules($country_id);
			if ($this->validate($rules)) { 
				$data_in = $this->get_column_values();				
				$this->mObj->update($data_in,$country_id);
				$this->notify_success('Record Updated Successfully');
				return redirect()->to(get_admin_path('country'));
			}
		}else{
			$data['update_data'] = $this->mObj->get($country_id);
		}
		$data['footer_includes'] = ['country_add_edit_js'];	
		echo $this->view_inner_template('country_add_edit',$data);
	}
	
	public function delete($country_id){
		$this->allowed('is_edit');
		$this->mObj->delete($country_id);
		$this->notify_success('Record Deleted Successfully');
		return redirect()->to(get_admin_path('country'));
	}
	
	private function save_uploaded_file(&$data){
		$file = $this->request->getFile('image');
		if($file->getName()){
			$file->move(ROOTPATH . 'public/uploads/',$file->getRandomName());
			$data['photo'] = $file->getName();
		}
	}
	
	private function get_column_values(){
		
		$data['status'] = $this->request->getPost('status');
		$this->save_uploaded_file($data);
		return $data;
	}
	
	private function get_validation_rules($country_id=""){
			$rules['status'] = ['label'=>'Status', 'rules' => 'trim|required'];
			if($this->request->getFile('image')->getName()){
				$rules['image'] = ['label'=>'Image', 'rules'=>'uploaded[image]|max_size[image,2048]|is_image[image]|max_dims[image,1920,1080]'];
			}
		return $rules;
	}
}