<?php
include 'connect/cms-config.php' ;
include 'requires/function.php' ;
$user_permission_check = 'all-permission' ;
include 'requires/session.php' ;

// keep parameter in value
$page = escapeString($_GET['page']) ;
$type = escapeString($_GET['type']) ;

// active page
$active_main_menu 	= 'dashboard' ;
$active_menu 		= 'dashboard' ;

// check query exsits
$mysqli_page = $mysqli->query("SELECT post_id, post_title, post_content FROM system_post
							   WHERE post_type = 'page-dashboard' AND post_categories = 'page-dashboard' AND post_trash = '0' LIMIT 1") ;
							   
// check if page exists
if ($mysqli_page->num_rows == 0){
	// insert into database
	$mysqli->query("INSERT INTO system_post
					(post_type, post_categories, post_date, post_modified, post_trash) VALUES
					('page-dashboard', 'page-dashboard', '".TODAYDATE."', '".TODAYDATE."', '0')") ;
	// set page id in variable s
	$page = $mysqli->insert_id ;
	// refresh page
	header("Location:page-dashboard.php?page=".$page."") ;
	exit ;
}else{
	
	// set query as array
	$row_page = $mysqli_page->fetch_array(MYSQLI_ASSOC) ;
	
	// set page id in variable
	$page = $row_page['post_id'] ;
	
	// update database
	if ( $boolean_admin && isset($type) && $type == 'edit' && $_POST['hide'] == 1 ){
		
		// keep value in variable
		$page_title = escapeString($_POST['title']) ;
		$page_title = ($page_title != '' ? $page_title : '') ;
		$page_content = resetString(escapeString($_POST['content'])) ;
		
		// check if name already exists.
		$check_status = checkTitle($page_title, $page) ;
		$title = $check_status['title'] ;
		$status = $check_status['status'] ;
		
		// update database
		$mysqli->query("UPDATE system_post SET
						post_title = '".$page_title."',
						post_content = '".$page_content."',
						post_status = '".$status."',
						post_link = '".$title."',
						post_modified = '".TODAYDATE."',
						post_trash = '0'
						WHERE post_id = '".$page."'") ;
		
		// refresh page
		$_SESSION['system_result'] = 'success-updated' ;
		header("Location:page-dashboard.php?page_mode=edit&page=".$page."&success=1") ;
		exit ;
		
	}
	
}

// start header here
include 'requires/page_header.php' ;
include 'requires/page_top.php' ;

?>
<link rel="stylesheet" href="<?= $require_path ?>css/dashboard.css" />

<div class="warper container-fluid">   	

	<div class="page-header"><h1><?= $lang['Dashboard'] ?> <small><?= $lang['page'] ?></small></h1></div>
    
    <?php
	if ($_SESSION['system_result'] != ''){
		switch($_SESSION['system_result']){
			case 'success-updated' :
				echo '<div class="result_success">'.$lang['thank_you_your_dashboard_has_been_updated'].'</div>' ;
			break ;
		}
		unset($_SESSION['system_result']) ;
	}
	?>


	<?php if ( $_SESSION['system_permission'] == 'admin' ){ 

		// all not yet assigned staff
		$mysqli_staff_noassigned = $mysqli->query( "SELECT COUNT(staff_id) as total FROM staff
												    WHERE ( staff_date_resigned IS NULL || staff_date_resigned = '0000-00-00' || staff_date_resigned >= '".TODAYDATE."' ) AND deleted_at IS NULL AND branch_id = '0'" ) ;
		$row_staff_noassigned    = $mysqli_staff_noassigned->fetch_assoc() ;
		$total_staff_noassigned  = $row_staff_noassigned['total'] ;


		// all active staff
		$mysqli_staff 			 = $mysqli->query( "SELECT COUNT(staff_id) as total FROM staff
												    WHERE ( staff_date_resigned IS NULL || staff_date_resigned = '0000-00-00' || staff_date_resigned >= '".TODAYDATE."' ) AND deleted_at IS NULL AND branch_id != '0'" ) ;
		$row_staff    		     = $mysqli_staff->fetch_assoc() ;
		$total_staff 		     = $row_staff['total'] ;


		// total branch
		$mysqli_branch 			 = $mysqli->query( "SELECT COUNT(branch_id) as total FROM branch
                               			            WHERE deleted_at IS NULL " ) ;		
		$row_staff_noassigned    = $mysqli_staff_noassigned->fetch_assoc() ;
		$row_branch    			 = $mysqli_branch->fetch_assoc() ;
		$total_branch  			 = $row_branch['total'] ;


		// passport / permit expiry within 2 months
		$date_startmonth         = TODAYDAY . ' 00:00:00' ;
		$date_endmonth           = date( "Y-m-d", strtotime("+2 months") ) . ' 23:59:59' ;
		$mysqli_passport 		 = $mysqli->query( "SELECT COUNT(staff_id) as total FROM staff
												    WHERE ( staff_date_resigned IS NULL || staff_date_resigned = '0000-00-00' || staff_date_resigned >= '".TODAYDATE."' ) AND deleted_at IS NULL AND branch_id != '0' AND country_id != '1' AND ( staff_permit_end BETWEEN '".$date_startmonth."' AND '".$date_endmonth."' OR staff_passportexpired BETWEEN '".$date_startmonth."' AND '".$date_endmonth."' )" ) ;
		$row_passport            = $mysqli_passport->fetch_assoc() ;
		$total_passport 		 = $row_passport['total'] ;

		$dashboards 			 = [
			[
				'title'          => 'Not Yet Assign Staff',
				'value' 	     => $total_staff_noassigned
			],
			[
				'title'          => 'Active Staff',
				'value' 	     => $total_staff
			],
			[
				'title'          => 'Total Branch',
				'value' 	     => $total_branch
			],
			[
				'title'          => 'Permit & Passport Within 2 Months',
				'value' 	     => $total_passport
			]
		] ;

		?>
		<ul class="dashboard-report-ul">
			<?php foreach ( $dashboards as $k => $v ){ ?>
				<li>
					<div class="dashboard-report-div">
						<div class="card border-3 border-top border-top-primary">
							<div class="card-body">
								<h5 class="text-muted"><?= $v['title'] ?></h5>
								<div class="metric-value d-inline-block">
									<h1 class="mb-1"><?= $v['value'] ?></h1>
								</div>
								<!-- <div class="metric-label d-inline-block float-right text-success font-weight-bold">
									<span class="icon-circle-small icon-box-xs text-success bg-success-light">
										<i class="fa fa-fw fa-arrow-up"></i>
									</span>
									<span class="ml-1">5.86%</span>
								</div> -->
							</div>
						</div>
					</div>
				</li>
			<?php } ?>
		</ul>
	<?php } ?>




	<script>
	window.onload = function() {

		// pie chart
		var piechart = new CanvasJS.Chart("piechartContainer", {
			animationEnabled: true,
			title: {
				text: "Desktop Search Engine Market Share - 2016"
			},
			data: [{
				type: "pie",
				startAngle: 240,
				yValueFormatString: "##0.00\"%\"",
				indexLabel: "{label} {y}",
				dataPoints: [
					{y: 79.45, label: "Google"},
					{y: 7.31, label: "Bing"},
					{y: 7.06, label: "Baidu"},
					{y: 4.91, label: "Yahoo"},
					{y: 1.26, label: "Others"}
				]
			}]
		});
		piechart.render() ;


		// bar chart
		var barchart = new CanvasJS.Chart("barchartContainer", {
			animationEnabled: true,
			title:{
				text: "Olympic Medals of all Times (till 2016 Olympics)"
			},
			axisY: {
				title: "Medals",
				includeZero: true
			},
			legend: {
				cursor:"pointer",
				itemclick : toggleDataSeries
			},
			toolTip: {
				shared: true,
				content: toolTipFormatter
			},
			data: [{
				type: "bar",
				showInLegend: true,
				name: "Gold",
				color: "gold",
				dataPoints: [
					{ y: 243, label: "Italy" },
					{ y: 236, label: "China" },
					{ y: 243, label: "France" },
					{ y: 273, label: "Great Britain" },
					{ y: 269, label: "Germany" },
					{ y: 196, label: "Russia" },
					{ y: 1118, label: "USA" }
				]
			},
			{
				type: "bar",
				showInLegend: true,
				name: "Silver",
				color: "silver",
				dataPoints: [
					{ y: 212, label: "Italy" },
					{ y: 186, label: "China" },
					{ y: 272, label: "France" },
					{ y: 299, label: "Great Britain" },
					{ y: 270, label: "Germany" },
					{ y: 165, label: "Russia" },
					{ y: 896, label: "USA" }
				]
			},
			{
				type: "bar",
				showInLegend: true,
				name: "Bronze",
				color: "#A57164",
				dataPoints: [
					{ y: 236, label: "Italy" },
					{ y: 172, label: "China" },
					{ y: 309, label: "France" },
					{ y: 302, label: "Great Britain" },
					{ y: 285, label: "Germany" },
					{ y: 188, label: "Russia" },
					{ y: 788, label: "USA" }
				]
			}]
		});
		barchart.render();

		function toolTipFormatter(e) {
			var str = "";
			var total = 0 ;
			var str3;
			var str2 ;
			for (var i = 0; i < e.entries.length; i++){
				var str1 = "<span style= \"color:"+e.entries[i].dataSeries.color + "\">" + e.entries[i].dataSeries.name + "</span>: <strong>"+  e.entries[i].dataPoint.y + "</strong> <br/>" ;
				total = e.entries[i].dataPoint.y + total;
				str = str.concat(str1);
			}
			str2 = "<strong>" + e.entries[0].dataPoint.label + "</strong> <br/>";
			str3 = "<span style = \"color:Tomato\">Total: </span><strong>" + total + "</strong><br/>";
			return (str2.concat(str)).concat(str3);
		}

		function toggleDataSeries(e) {
			if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
				e.dataSeries.visible = false;
			}
			else {
				e.dataSeries.visible = true;
			}
			barchart.render();
		}
	}
	</script>

	<div class="dashboard_section">
		<div class="row dashboard_chart">
			<div class="col-sm-6">
				<div id="piechartContainer" class="chart_div"></div>
			</div>
			<div class="col-sm-6">
				<div id="barchartContainer" class="chart_div"></div>
			</div>
		</div>
	</div>




	<?php if ( permissionCheck($row_user, 'dashboard-view') ){ ?>
		<div class="panel panel-default">
	        <div class="panel-heading">Monthly Achievement</div>
	        
	        <div class="panel-body">
	        	<iframe id="dashboard-iframe" src="page-dashboard-iframe.php" style="border:none; width: 100%;">
	        	</iframe>
	        </div>
	    </div>

		<?php
		$array_table = [ [
				'title' => 'TASK',
				'query' => "SELECT task_id FROM task a 
							WHERE a.deleted_at IS NULL and a.status in ('pending', 'assigned', 'resubmit', 'progress') " . $user_branch_permission_sql_task,
				'url'   => "task.php?search_type%5B%5D=pending&search_type%5B%5D=assigned&search_type%5B%5D=resubmit&search_type%5B%5D=progress&page_mode=list"
			], [
				'title' => 'SUGGESTION',
				'query' => "SELECT a.suggestion_id FROM suggestion a
						    LEFT JOIN staff b ON ( a.staff_id = b.staff_id )
						    WHERE a.deleted_at IS NULL and a.status IN ( 'pending' ) " . $user_branch_permission_sql_b,
				'url'   => "app-suggestion.php?page_mode=list&search_type=pending"
			], [
				'title' => 'REQUEST',
				'query' => "SELECT a.request_id FROM request a
						    LEFT JOIN staff b ON ( a.staff_id = b.staff_id )
						    WHERE a.deleted_at IS NULL and a.status IN ('pending', 'awaiting-arrival', 'awaiting-collection') " . $user_branch_permission_sql_b,
				'url'   => "app-request.php?page_mode=list&search_type%5B%5D=pending&search_type%5B%5D=awaiting-arrival&search_type%5B%5D=awaiting-collection"
			], [
				'title' => 'GRIEVANCE',
				'query' => "SELECT a.grievance_id FROM grievance a
						    LEFT JOIN staff b ON ( a.staff_id = b.staff_id )
						    WHERE a.deleted_at IS NULL and a.status IN ( 'pending' ) " . $user_branch_permission_sql_b,
				'url'   => "app-grievance.php?page_mode=list&search_type=pending"
			], [
				'title' => 'Redeem',
				'query' => "SELECT a.redeem_id as item_file FROM staff_redeem a
						    LEFT JOIN staff b ON ( a.staff_id = b.staff_id )
						    WHERE a.deleted_at IS NULL and a.status IN ('pending', 'awaiting-arrival', 'awaiting-collection') " . $user_branch_permission_sql_b,
				'url'   => "app-redeem.php?page_mode=all&search_type%5B%5D=pending&search_type%5B%5D=awaiting-arrival&search_type%5B%5D=awaiting-collection"
			], [
				'title' => 'ASSOCIATION',
				'query' => "SELECT a.view_id FROM staff_association a
						    LEFT JOIN staff b ON ( a.staff_id = b.staff_id )
						    WHERE a.deleted_at IS NULL and a.status IN ( 'pending' ) " . $user_branch_permission_sql_b,
				'url'   => "app-association.php?page_mode=view_all&search_type[]=pending"
			], [
				'title' => 'TRAINING',
				'query' => "SELECT a.view_id FROM staff_training a
						    LEFT JOIN staff b ON ( a.staff_id = b.staff_id )
						    WHERE a.deleted_at IS NULL AND a.status IN ( 'pending' ) " .$user_branch_permission_sql_b,
				'url'   => "app-training.php?page_mode=view_all&search_type[]=pending"
			], [
				'title' => 'HEADCOUNT',
				'query' => "SELECT a.formheadcount_id FROM formheadcount a
							LEFT JOIN staff b ON ( a.staff_id = b.staff_id )
							WHERE a.deleted_at IS NULL AND a.status IN ( 'pending' ) " . $user_branch_permission_sql_b,
				'url'   => "app-form-headcount.php?page_mode=list&search_type=pending"
			], [
				'title' => 'NOMINATION',
				'query' => "SELECT a.formnomination_id FROM formnomination a
							LEFT JOIN staff b ON ( a.staff_id = b.staff_id )
							WHERE a.deleted_at IS NULL AND a.status IN ( 'pending' ) ".$user_branch_permission_sql_b,
				'url'   => "app-form-nomination.php?page_mode=list&search_type=pending"
			], [
				'title' => 'RESIGNATION',
				'query' => "SELECT a.formresignation_id FROM formresignation a
							LEFT JOIN staff b ON ( a.staff_id = b.staff_id )
							WHERE a.deleted_at IS NULL AND a.status IN ( 'pending' ) ".$user_branch_permission_sql_b,
				'url'   => "app-form-resignation.php?page_mode=list&search_type=pending"
			]
		] ;
		?>

	    <div class="panel panel-default">
	        <div class="panel-heading">Current Pending List</div>
	        <div class="panel-body" style="display: flex; flex-wrap: wrap;">
	        	<?php foreach ( $array_table as $k_table => $v_table ) {
	        		$select_table = $mysqli->query( $v_table['query'] ) ;
	        		$count_table  = $select_table->num_rows ;

	        		?>
	        		<table cellpadding="0" cellspacing="0" border="0" class="responsive table table-striped table-bordered dashboard-tab">
						<thead>
							<tr>
								<th><?= $v_table['title'] ?></th>
							</tr>
						</thead>
						<tbody>
							<tr class="odd gradeX">
								<td class="border_none">
									<a target="_blank" href="<?= $v_table['url'] ?>" style="text-decoration:none;">
										<div style="height: 100%;display: flex;position: relative;justify-content: center;align-items: center;">
											<h1 style="font-size:70px;padding:0;margin:0;"><?= $count_table ?></h1>
										</div>
									</a>
								</td>
							</tr>
						</tbody>
					</table>
	        	<?php } ?>
			</div>
	    </div>
	<?php } ?>


	<?php if ( permissionCheck($row_user, 'dashboard-view') ){ ?>
	    <div class="panel panel-default">
	        <div class="panel-heading">Weekly Chart Report</div>
	        <div class="panel-body">
	        	<iframe id="chart_iframe" src="chart_iframe.php" style="border:none; height: 100vh; width: 100%;"></iframe>

	        	<script>
					$(document).ready(function(){
						$('#dashboard-iframe').load(function() {
							setIframeHeight2('dashboard-iframe') ;
						});

						$('#chart_iframe').load(function() {
							setIframeHeight('chart_iframe') ;
						});
					}) ;
				</script>
	        </div>
	    </div>
	<?php } ?>


    <div class="panel panel-default">
		<div class="panel-heading"></div>
		<div class="panel-body">
        	
            <form method="post" class="form-horizontal" id="quotationForm" action="page-dashboard.php?page=<?= $page ?>&type=edit" novalidate="novalidate">
            	
                <div class="form-group">
                    <div class="col-sm-2 control-label">Title</div>
                    <div class="col-sm-7">
                    	<input type="text" name="title" class="form-control ui-search-input" value="<?= dataFilter($row_page['post_title']) ?>" <?= ($boolean_admin ? '' : 'readonly') ?> placeholder="Title" />
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-2 control-label"><?= $lang['Description'] ?></div>
                    <div class="col-sm-7">
						<textarea name="content" class="content" id="editor1" <?= ( $boolean_admin ? '' : 'readonly' ) ?> rows="10" cols="80"><?= dataFilter($row_page['post_content']) ?></textarea>
						<script> CKEDITOR.replace("editor1") ; </script>
                    </div>
                </div>
                <?php if ( $boolean_admin ){ ?>
					<div class="form-group">
						<div class="col-sm-2 control-label"></div>
						<div class="col-sm-7">
							<button type="submit" class="btn btn-purple" style="float:right">Submit</button>
							<input type="hidden" name="page_status" value="edit">
							<input type="hidden" name="hide" value="1">
						</div>
					</div>
				<?php } ?>
            </form>
            
		</div>
	</div>

</div>



<?php
// footer
include 'requires/page_footer.php' ;
?>