<?php namespace App\Controllers\Admin;

class Upload extends AdminController
{
	private $mObj;
	
	public function __construct(){		
        $this->mObj = model('App\Models\Admin\UploadModel');
		$this->menu_id = 7;
    }
	
	public function index(){
		$this->allowed('is_list');
		$data['footer_includes'] = ['upload_list_js'];		
		echo $this->view_inner_template('upload_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');
	    $data['form_heading'] = "Upload Add";
		
		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('upload'));
			}
		}
		$data['footer_includes'] = ['upload_add_edit_js'];	
		echo $this->view_inner_template('upload_add_edit',$data);
	}
	

	
	public function edit($upload_id){
		$this->allowed('is_edit');
		$data['form_heading'] = "Upload Edit";
		if($this->request->getMethod() === 'post'){
			$rules = $this->get_validation_rules($upload_id);
			if ($this->validate($rules)) { 
				$data_in = $this->get_column_values();
				$this->mObj->update($data_in,$upload_id);
				$this->notify_success('Record Updated Successfully');
				return redirect()->to(get_admin_path('upload'));
			}
		}else{
			$data['update_data'] = $this->mObj->get($upload_id);
		}
		$data['footer_includes'] = ['upload_add_edit_js'];	
		echo $this->view_inner_template('upload_add_edit',$data);
	}
	
	
	
	public function delete($upload_id){
		$this->allowed('is_edit');
		$this->mObj->delete($upload_id);
		$this->notify_success('Record Deleted Successfully');
		return redirect()->to(get_admin_path('upload'));
	}
	
    private function get_column_values(){
		$data['title'] = $this->request->getPost('title');
		$this->save_uploaded_file($data);
		return $data;
	}
	
	private function save_uploaded_file(&$data){
		$file = $this->request->getFile('file_name');
		if($file->getName()){
			$file->move(ROOTPATH . 'public/uploads/',$file->getRandomName());
			$data['file_name'] = $file->getName();
		}
	}
	
	private function get_validation_rules($upload_id=""){
		$rules['title'] = ['label'=>'Title', 'rules' => 'trim|required|pr_callback['.$this->mObj->is_unique_title($this->request->getPost('title'),$upload_id).']'];
		if($this->request->getFile('file_name')->getName()){
			$rules['file_name'] = ['label'=>'File', 'rules'=>'uploaded[file_name]|max_size[file_name,5000]'];
		}
		return $rules;
	}
}