<?php
/**
 * PHPExcel
 *
 * Copyright (c) 2006 - 2015 PHPExcel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @category   PHPExcel
 * @package    PHPExcel
 * @copyright  Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
 * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt	LGPL
 * @version    ##VERSION##, ##DATE##
 */

date_default_timezone_set('Asia/Kuala_Lumpur');

/** Include PHPExcel */
include 'connect/cms-config.php' ;
include 'requires/function.php' ;
include 'requires/session.php' ;
include_once('PhpExcel/PHPExcel.php');
include_once('PhpExcel/PHPExcel/IOFactory.php') ;

// today date
$date = date('Y-m-d H:i:s',time()) ;
// remove l w h
//$post_array = array_diff($post_array, array('post_id', 'l', 'w', 'h'));
// rearrange array key
//$post_array = array_values($post_array);
// product import						
if(isset($_FILES['excel_file']['name'])){

    $file_name = $_FILES['excel_file']['name'];
    $ext = pathinfo($file_name, PATHINFO_EXTENSION);

    //Checking the file extension
    if($ext == "xlsx"){

            $file_name = $_FILES['excel_file']['tmp_name'];
            $inputFileName = $file_name;

    /**********************PHPExcel Script to Read Excel File**********************/

        //  Read your Excel workbook
        try {
            $inputFileType = PHPExcel_IOFactory::identify($inputFileName); //Identify the file
            $objReader = PHPExcel_IOFactory::createReader($inputFileType); //Creating the reader
            $objPHPExcel = $objReader->load($inputFileName); //Loading the file
        } catch (Exception $e) {
            die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) 
            . '": ' . $e->getMessage());
        }

        //  Get worksheet dimensions
        $sheet = $objPHPExcel->getSheet(0);     //Selecting sheet 0
        $highestRow = $sheet->getHighestRow();     //Getting number of rows
		//$highestRow = 5;     //Getting number of rows
        $highestColumn = $sheet->getHighestColumn();     //Getting number of columns 

		$crow = 0;

		//initial array
		$certain_pic_fail = $pic_fail = $area_fail = $profile_fail = array();
		$success_count = 0;
		$array_error = [];

        //  Loop through each row of the worksheet in turn -> $row is for starting point
        for ($row = 2; $row <= $highestRow; $row++) {
        	//  Read a row of data into an array
            $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, 
            NULL, TRUE, FALSE);

            if($rowData[0][0] != ''){
	            //gender
	            if($rowData[0][3]!= ''){
		            $select_gender = $mysqli->query("SELECT gender_id FROM master_gender WHERE gender_desc = '".$rowData[0][3]."' LIMIT 1");
		            $gender_id = $select_gender->fetch_assoc()['gender_id'];
		        }else{
		        	$gender_id = 0;
		        }

	            //calculate probation end date
	            if($rowData[0][7] != ""){
	            	if($rowData[0][4] != ''){
	            		$start_date = date('Y-m-d', $rowData[0][4]);
	            		$end_date = date('Y-m-d', strtotime("+".$rowData[0][7]." month", $start_date));
	            	}
	            }

	            //detect working type
	            if($rowData[0][10] != ''){
	            	$select_working_group = $mysqli->query("SELECT * FROM setting_working_group WHERE group_name = '".$rowData[0][10]."'");
	            	$working_group_id = $select_working_group->fetch_assoc()['group_id'];
	            }else{
	            	$working_group_id = 0;
	            }

	            $staff_idno = $rowData[0][0];
	            $staff_fullname = $mysqli->real_escape_string($rowData[0][1]);
	            $staff_username = $rowData[0][2];
	            $staff_password = passwordEncrypt($rowData[0][0]);
	            $staff_gender   = $gender_id;
	            $staff_join_date = $rowData[0][4] != '' ? date('Y-m-d', ($rowData[0][4] - 25569)*86400) : '';
	            $staff_confirm_date = $rowData[0][5] != '' ? date('Y-m-d', ($rowData[0][5]- 25569)*86400) : NULL;
	            $staff_terminate_date = $rowData[0][6] != '' ? date('Y-m-d', ($rowData[0][6]- 25569)*86400) : NULL;
	            $staff_probation = $end_date;
	            $staff_email = $rowData[0][8];
	            $staff_mobile = $rowData[0][9];
	            $staff_working_type = $working_group_id;

	            $result = false;
	            if($mysqli->query("INSERT INTO staff (staff_idno, staff_name, staff_email, staff_username, staff_password, staff_mobileno, gender_id, staff_date_joined, staff_date_confirmed, staff_date_resigned, staff_probation_end, group_id, created_at) VALUES('".$staff_idno."', '".$staff_fullname."', '".$staff_email."', '".$staff_username."', '".$staff_password."', '".$staff_mobile."', '".$staff_gender."', '".$staff_join_date."', '".$staff_confirm_date."', '".$staff_terminate_date."', '".$staff_probation."', '".$staff_working_type."', '".TODAYDATE."')")){

	            	$result = true;
	            }

	            if(!$result){
	            	$array_error[] = $row;
	            }
	        }
        }

    }
}

if(arrayCheck($array_error)){
	echo (implode(",", $array_error));
}else{
	echo ("SUCCESS");
}
?>
<html>
<head></head>
<body>
	<form enctype="multipart/form-data" method="post" action="import-excel.php">
		<input type="file" name="excel_file" onchange="if(confirm('Are you sure want to import the file?'))this.form.submit();else this.form.reset()"/>
	</form>
</body>
</html>