<?php namespace App\Http\Controllers;

use App\Models\Datasopik;
use App\Library\DataHelpers;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
use Validator, Input, Redirect ;
use Illuminate\Support\Facades\DB;


class DatasopikController extends Controller {

	protected $layout = "layouts.main";
	protected $data = array();	
	public $module = 'datasopik';
	static $per_page	= '10';
	
	public function __construct() 
	{
		parent::__construct();
		$this->model = new Datasopik();
		
		$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'		=> 'datasopik',
			'pageUrl'			=>  url('datasopik'),
			'return' 			=> 	self::returnUrl()	
		);	
			
				
	} 
	public function index()
	{
		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['column'] = $cols ;	
		$this->data['access']		= $this->access;	
		$this->data['setting'] 		= $this->info['setting'];
		return view('datasopik.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 'export':
				return $this->getExport( $request );
				break;
			case 'servefile':
				return $this->serveFile( $request );
				break;
			case 'servepdf':
				return $this->servePdf( $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;		
			case 'viewfile':
				return $this->viewFile( $request );
				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);
		}

		$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')
				{
					if($field['field'] == "filedata")
					{
						$values[$field['field']] = '<a href="javascript:void(0)" onclick="viewFile(\''.$row->{$field['field']}.'\')"><i class="fa fa-eye"></i> Lihat</a>';
					} else {
						$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')
			));

		} 		

	}

	
	public function viewFile( Request $request)
	{
		$fileName = $request->input('file');
		$keperluan = $request->input('keperluan');

		if (empty($keperluan)) {
			return response()->json(array('success' => false, 'message' => 'Keperluan harus diisi.'));
		}

		$filePath = public_path('uploads/file_sop_ik/' . $fileName);

		if (!file_exists($filePath)) {
			return response()->json(array('success' => false, 'message' => 'File tidak ditemukan.'));
		}

		// Encrypt payload so the filename is not exposed in the URL
		$token = encrypt(['file' => $fileName, 'keperluan' => $keperluan, 'expire' => now()->addMinutes(30)->timestamp]);

		// Save view log
		DB::table('data_log_sopik')->insert([
			'keperluan'  => $keperluan,
			'username'   => \Session::get('uid'),
			'view_date'  => now(),
			'view_file'  => $fileName,
		]);

		// Return URL pointing to servePdf (raw bytes) for PDF.js in frontend
		$serveUrl = url('datasopik/servepdf') . '?token=' . urlencode($token);


		return response()->json(array('success' => true, 'fileUrl' => $serveUrl));
	}

	private function validateFileToken( Request $request)
	{
		if (!\Auth::check()) abort(403);
		try {
			$payload = decrypt($request->input('token'));
		} catch (\Exception $e) {
			abort(403, 'Token tidak valid.');
		}
		if (now()->timestamp > $payload['expire']) abort(403, 'Link sudah kadaluarsa.');
		return $payload;
	}

	public function serveFile( Request $request)
	{
		$payload = $this->validateFileToken($request);

		// Build URL to the raw-bytes endpoint (used internally by PDF.js only)
		$pdfUrl    = json_encode(url('datasopik/servepdf') . '?token=' . urlencode($request->input('token')));
		$pageTitle = json_encode('Dokumen SOP/IK');

		$html = <<<HTML
<!DOCTYPE html>
<html lang="id">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Dokumen SOP/IK</title>
	<style>
		* { margin:0; padding:0; box-sizing:border-box; }
		html, body { width:100%; height:100%; background:#525659; overflow:hidden; }
		#viewer { width:100%; height:100%; overflow-y:auto; display:flex; flex-direction:column; align-items:center; padding:20px 0; gap:12px; }
		canvas { display:block; box-shadow:0 2px 12px rgba(0,0,0,.6); background:#fff; }
		#loading { color:#ccc; font:16px sans-serif; margin-top:40px; }
	</style>
</head>
<body>
	<div id="viewer"><p id="loading">Memuat dokumen...</p></div>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
	<script>
		pdfjsLib.GlobalWorkerOptions.workerSrc =
			'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';

		// Block right-click
		document.addEventListener('contextmenu', function(e){ e.preventDefault(); });

		// Block Ctrl+S / Ctrl+P / Ctrl+U / F12
		document.addEventListener('keydown', function(e) {
			var blocked = ['s','p','u'];
			if ((e.ctrlKey || e.metaKey) && blocked.indexOf(e.key.toLowerCase()) !== -1) {
				e.preventDefault(); return false;
			}
			if (e.key === 'F12') { e.preventDefault(); return false; }
		});

		var pdfUrl = {$pdfUrl};
		var viewer = document.getElementById('viewer');

		pdfjsLib.getDocument({ url: pdfUrl, withCredentials: true }).promise
			.then(function(pdf) {
				document.getElementById('loading').remove();
				var scale = Math.min(1.5, (window.innerWidth - 40) / 595);
				var renders = [];
				for (var i = 1; i <= pdf.numPages; i++) {
					renders.push((function(pageNum) {
						return pdf.getPage(pageNum).then(function(page) {
							var vp = page.getViewport({ scale: scale });
							var canvas = document.createElement('canvas');
							canvas.width  = vp.width;
							canvas.height = vp.height;
							viewer.appendChild(canvas);
							return page.render({ canvasContext: canvas.getContext('2d'), viewport: vp }).promise;
						});
					})(i));
				}
				return renders.reduce(function(p, r){ return p.then(function(){ return r; }); }, Promise.resolve());
			})
			.catch(function(err) {
				viewer.innerHTML = '<p style="color:#f88;font:14px sans-serif;margin:40px">Gagal memuat dokumen: ' + err.message + '</p>';
			});
	</script>
</body>
</html>
HTML;

		return response($html, 200, [
			'Content-Type'   => 'text/html; charset=utf-8',
			'Cache-Control'  => 'no-store, no-cache',
			'X-Frame-Options'=> 'SAMEORIGIN',
		]);
	}

	public function servePdf( Request $request)
	{
		$payload  = $this->validateFileToken($request);
		$filePath = public_path('uploads/file_sop_ik/' . basename($payload['file']));

		if (!file_exists($filePath)) abort(404, 'File tidak ditemukan.');

		return response()->stream(function () use ($filePath) {
			$stream = fopen($filePath, 'rb');
			fpassthru($stream);
			fclose($stream);
		}, 200, [
			'Content-Type'        => 'application/pdf',
			'Content-Disposition' => 'inline',
			'Content-Length'      => filesize($filePath),
			'Cache-Control'       => 'no-store, no-cache',
			'Pragma'              => 'no-cache',
		]);
	}

}