<?php namespace App\Http\Controllers;

use App\Models\Dataupahtebang;
use App\Library\DataHelpers;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
use Validator, Input, Redirect ; 

class DataupahtebangController extends Controller {

	protected $layout = "layouts.main";
	protected $data = array();	
	public $module = 'dataupahtebang';
	static $per_page	= '10';
	
	public function __construct() 
	{
		parent::__construct();
		$this->model = new Dataupahtebang();
		
		$this->info = $this->model->makeInfo( $this->module);
		$this->access = $this->model->validAccess($this->info['id']);
	
		$this->data = array(
			'pageTitle'			=> 	$this->info['title'],
			'pageNote'			=>  $this->info['note'],
			'pageModule'		=> 'dataupahtebang',
			'pageUrl'			=>  url('dataupahtebang'),
			'return' 			=> 	self::returnUrl()	
		);	
			
				
	} 
	public function index(Request $request)
	{
		if(!\Auth::check()) 
			return redirect('user/login')->with('status', 'error')->with('message','You are not login');

		$this->access = $this->model->validAccess($this->info['id'] , session('gid'));
		if($this->access['is_view'] ==0) 
			return redirect('dashboard')->with('message',__('core.note_restric'))->with('status','error');
		
		$this->data['setting'] 		= $this->info['setting'];
		$this->data['tableForm'] 	= $this->info['config']['forms'];
		$this->data['tableGrid'] 	= $this->info['config']['grid'];
		usort($this->data['tableGrid'], "SiteHelpers::_sort");
			$cols = '{"data":"rowId"},';
			if($this->data['setting']['view-method'] =='expand'){
				$cols .= '{"className": "details-control","orderable": false,"data": null,"defaultContent": ""},';
			}		
				
			foreach($this->data['tableGrid'] as $field)
			{				
				
				if($field['view'] =='1')
				{
					$cols .= '{"data":"'.$field['field'].'"},';
				}						
			}
			$cols .= '{"data":"action"},';
			$this->data['unit'] = $request->input('unit');
		$this->data['column'] = $cols ;	
		$this->data['access']		= $this->access;	
		$this->data['setting'] 		= $this->info['setting'];
		return view('dataupahtebang.index',$this->data);
	}
	function create( Request $request ) 
	{
		$this->hook( $request  );
		if($this->access['is_add'] ==0) 
			return redirect('dashboard')->with('message', __('core.note_restric'))->with('status','error');

		$this->data['row'] = $this->model->getColumnTable( $this->info['table']); 
		
		$this->data['setting'] 		= $this->info['setting'];
		$this->data['id'] = '';
		return view($this->module.'.form',$this->data);
	}
	function edit( Request $request , $id ) 
	{
		$this->hook( $request , $id );
		if(!isset($this->data['row']))
			return redirect($this->module)->with('message','Record Not Found !')->with('status','error');
		if($this->access['is_edit'] ==0 )
			return redirect('dashboard')->with('message',__('core.note_restric'))->with('status','error');
		$this->data['row'] = (array) $this->data['row'];
		
		$this->data['setting'] 		= $this->info['setting'];
		$this->data['id'] = $id;
		return view($this->module.'.form',$this->data);
	}
	function show( Request $request , $id ) 
	{
		/* Handle import , export and view */
		$task =$id ;
		switch( $task)
		{
			case 'search':
				return $this->getSearch();
				break;
			case 'lookup':
				return $this->getLookup($request );
				break;
			case 'comboselect':
				return $this->getComboselect( $request );
				break;
			case 'import':
				return $this->getImport( $request );
			case 'removefiles':
				return $this->getRemovefiles( $request );	
				break;

			case 'tarikdataupah':
				return $this->tarikdataupah($request);
				break;
			case 'downloadexcel':
				return $this->downloadExcel($request);
				break;	
			case 'export':
				return $this->getExport( $request );
				break;
			default:
				$this->hook( $request , $id );
				if(!isset($this->data['row']))
					return redirect($this->module)->with('message','Record Not Found !')->with('status','error');

				if($this->access['is_detail'] ==0) 
					return redirect('dashboard')->with('message', __('core.note_restric'))->with('status','error');

				return view($this->module.'.view',$this->data);	
				break;		
		}
	}	
	public function store( Request $request){

		$task = $request->input('action_task');
		switch ($task)
		{
			default:
				return $this->postData( $request);
				break;
			case 'save':
				$rules = $this->validateForm();
				$validator = Validator::make($request->all(), $rules);
				if ($validator->passes()) 
				{
					$data = $this->validatePost( $request );
					$id = $this->model->insertRow($data , $request->input( $this->info['key']));
					
					/* Insert logs */
					$this->model->logs($request , $id);
					return response()->json(array('status'=>'success','message'=> __('core.note_success')));	
					
				} 
				else {
					$message = $this->validateListError(  $validator->getMessageBag()->toArray() );
					return response()->json(array(
						'message'	=> $message,
						'status'	=> 'error'
					));	
				}
				break;
			case 'delete':
				return $result = $this->destroy( $request );
				break;

			case 'import':
				return $this->PostImport( $request );
				break;

			case 'copy':
				$result = $this->copy( $request );
				return response()->json($result);
				break;		

		}
	}
	public function postData( $request)
	{ 
		
		$this->access = $this->model->validAccess($this->info['id'] , session('gid'));

		$tables 	= $this->info['config']['grid'];
		$cols = array();
		foreach($tables as $field)
		{				
			//$cols[$this->info['key']]	= array('db'=> $field['alias'] ,$this->info['key'] );
			if($field['view'] =='1')
			{
				$cols[] = array('db'=> $field['alias'],'dt'=> $field['field'] );
			}					
		}
		$conf = DataHelpers::simple($request->all(),$cols);
		$filter =  '';
		if(!is_null($request->input('search')))
		{
			$filter .= $this->liveSearch( $request);
		}

		if(!is_null($request->input('unit')))
		{
			$filter .= " AND left(no_spta,4) = '".$request->input('unit')."' ";
		}

		$params = array(
			'page'		=> $conf['page'] ,
			'limit'		=> $conf['limit'] ,
			'sort'		=> ($conf['order']['sort'] !='' ? $conf['order']['sort'] : $this->info['setting']['orderby']) ,
			'order'		=> ($conf['order']['by'] !='' ? $conf['order']['by'] : $this->info['setting']['ordertype']),
			'params'	=> $filter,
			'global'	=> (isset($this->access['is_global']) ? $this->access['is_global'] : 0 )
		);

		

		$results = $this->model->getRows($params);
		
		$array = array();
		foreach($results['rows'] as $row)
		{
			$values = array();
			$values['rowId'] = $row->{$this->info['key']};
			foreach($tables as $field)
			{			
				
				if($field['view'] =='1')
				{
					$values[$field['field']] = \SiteHelpers::formatRows($row->{$field['field']}, $field , $row);
				}	
			}
			$values['action'] =  \SiteHelpers::buttonAction($this->module,$this->access ,$row->{$this->info['key']} ,$this->info['setting']) ;
			$array[] = $values; 	
		}
		
		$data = array(
			'draw'			=> (!is_null($request->input('draw')) ? intval($request->input('draw') ) : 0), 
			'recordsTotal'	=> $results['total'] ,
			'recordsFiltered'	=> $results['total'],
			'data'				=> $array

		);
		return response()->json($data);
	}

	public function destroy( Request $request)
	{

		if(!\Auth::check()) 
			return response()->json(array(
				'status'=>'error',
				'message'=> 'You are not login'
			));

		$this->access = $this->model->validAccess($this->info['id'] , session('gid'));
		if($this->access['is_remove'] ==0) 
			return response()->json(array('status'=>'error','message'=> __('core.note_restric')));	


		// delete multipe rows 
		if(count($request->input('ids')) >=1)
		{
			$this->model->destroy($request->input('ids'));
			
			return response()->json(array(
				'status'=>'success',
				'message'=> __('core.note_success_delete')
			));
		} else {
			return response()->json(array(
				'status'=>'error',
				'message'=> __('core.note_error')
			));

		} 		

	}

	function downloadExcel(Request $request)
	{
		if(!\Auth::check()) 
			return response()->json(array(
				'status'=>'error',
				'message'=> 'You are not login'
			));

		$this->access = $this->model->validAccess($this->info['id'] , session('gid'));
		if($this->access['is_excel'] ==0) 
			return response()->json(array('status'=>'error','message'=> __('core.note_restric')));	

		$filter = '';
		if(!is_null($request->input('unit')))
		{
			$filter .= " AND left(no_spta,4) = '".$request->input('unit')."' ";
		}
		if(!is_null($request->input('tgl1')) && !is_null($request->input('tgl2')))
		{
			$filter .= " AND tgl_timbang BETWEEN '".$request->input('tgl1')."' AND '".$request->input('tgl2')."' ";
		}
		// $filter = $this->liveSearch($request);
		$results = $this->model->getRows(array(
			'params' => $filter,
			'global' => (isset($this->access['is_global']) ? $this->access['is_global'] : 0 )
		));

		return $this->exportExcel($results['rows'], $this->info['config']['grid'], 'Data Upah Tebang');
	}

	function exportExcel($rows, $grid, $title = 'Export Data')
	{
		$filename = str_replace(' ', '_', $title) . '_' . date('Ymd_His') . '.xlsx';

		// Header kolom
		$header = [];
		foreach ($grid as $field) {
			if ($field['view'] == '1') {
				$header[] = $field['label'];
			}
		}

		// Data isi
		$data = [];
		foreach ($rows as $row) {
			$item = [];
			foreach ($grid as $field) {
				if ($field['view'] == '1') {
					$item[] = strip_tags(\SiteHelpers::formatRows($row->{$field['field']}, $field, $row));
				}
			}
			$data[] = $item;
		}

		// Buat file Excel menggunakan PhpSpreadsheet
		$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
		$sheet = $spreadsheet->getActiveSheet();
		$sheet->fromArray($header, NULL, 'A1');
		$sheet->fromArray($data, NULL, 'A2');

		// Output ke browser
		$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
		ob_start();
		$writer->save('php://output');
		$excelOutput = ob_get_clean();

		return response($excelOutput, 200, [
			'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
			'Content-Disposition' => 'attachment; filename="' . $filename . '"',
			'Cache-Control' => 'max-age=0',
		]);
	}

	function tarikdataupah(Request $request){

	}

	function getcookielogin(){
		$url = "https://kwm.prodis.sinergigula.com/index.php/user/postlogin";

		$data = [
			'username' => 'pusat.kso',
			'password' => 'pusat.kso'
		];
		
		$cookie = "ci_session=a%3A6%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22677c985afd7cca79976781ce45847fa9%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A14%3A%22".$this->myipaddress()."%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A117%3A%22".urlencode($_SERVER['HTTP_USER_AGENT'])."%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1739174392%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3Bs%3A4%3A%22lang%22%3Bs%3A2%3A%22en%22%3B%7Dc9f7347c8cb35c0e99abc9930aff63ecec15ce59"; // Gantilah dengan sesi yang valid
		
		$headers = [
			"Content-Type: application/x-www-form-urlencoded",
			"Upgrade-Insecure-Requests: 1",
			"User-Agent: ".$_SERVER['HTTP_USER_AGENT'],
			"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
			"Referer: https://kwm.prodis.sinergigula.com/index.php/user/login",
			"Cookie: $cookie"
		];
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_HEADER, true); // Ambil juga header respons
		
		$response = curl_exec($ch);
		$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
		$header = substr($response, 0, $header_size);
		$body = substr($response, $header_size);
		curl_close($ch);
		
		// Cari Set-Cookie di header
		preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $header, $matches);
		$cookies = $matches[1];
		
		// Tampilkan Set-Cookie
		// echo "Set-Cookie dari response:\n";
		return $cookies[3];

	}

	function myipaddress(){
		// Ambil alamat IP publik
		$ch = curl_init("https://ipinfo.io/ip");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$ip = curl_exec($ch);
		curl_close($ch);
	
		return trim($ip);
	}
}