<?php
include 'connect/cms-config.php' ;
include 'requires/function.php' ;
include 'requires/session.php' ;

// mode type | all list | new | edit
if ( !permissionCheck($row_user, 'import-point-view') ){
    echo '<script>alert("Sorry You Don\'t Have The Permission.")</script>';

    header('Location: index.php') ;
    exit ;
}


$active_main_menu = 'import' ;
$active_sub_menu  = 'import-point' ;
$active_menu      = 'import-point' ;  

$staff_all        = [] ; 
$mysqli_staff     = $mysqli->query("SELECT staff_idno, staff_id, branch_id FROM staff WHERE deleted_at IS NULL" . $user_branch_permission_sql) ;
if ( $mysqli_staff->num_rows > 0 ){
    while($row_staff = $mysqli_staff->fetch_array(MYSQLI_ASSOC)){
        $staff_all[$row_staff['staff_idno']] = $row_staff ;
    }
}

if(isset($_FILES['import-excel']['name'])){

    include 'PhpExcel/PHPExcel.php' ;

    $file_name  = $_FILES['import-excel']['name'];
    $ext        = pathinfo($file_name, PATHINFO_EXTENSION);

    //Checking the file extension
    if($ext == "xlsx"){
        $file_name = $_FILES['import-excel']['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());    
            header("location: hr-staff.php?page_mode=staff-attendance&result=error&msg=".urlencode($e->getMessage()));
            exit;
        }
        // ##################################################################################
        //                      Setting excel
        // ##################################################################################
        $sheet1 = $objPHPExcel->getSheet(0);     //Selecting sheet 0
        $highestRow1 = $sheet1->getHighestRow();     //Getting number of rows
        $highestColumn1 = $sheet1->getHighestColumn();     //Getting number of columns 
        //  Loop through each row of the worksheet in turn -> $row is for starting point
        for ( $row = 2; $row <= $highestRow1; $row++ ) {
            //  Read a row of data into an array
            $rowData    = $sheet1->rangeToArray('A' . $row . ':' . $highestColumn1 . $row, NULL, TRUE, FALSE);
            $rowData2[] = $rowData[0] ;
        }

        if( isset($rowData2) ){

            $setting_point = $mysqli->query( "SELECT point_id, point_type FROM setting_point WHERE deleted_at IS NULL AND point_from = 'adjustment' AND point_type IN ( 'plus', 'minus' ) AND difficulty = 'normal'" ) ;
            if ( $setting_point->num_rows > 0 ){
                $setting_point_list        = [] ;
                while ( $row_setting_point = $setting_point->fetch_assoc() ){
                    $setting_point_list[$row_setting_point['point_type']]  = $row_setting_point['point_id'] ;
                }

                $update_branchid  = '' ;
                $error_stafflist  = [] ;
                $error_staff      = 0 ;
                $error_typelist   = [] ;
                $error_type       = 0 ;
                $update_list      = [] ;
                foreach ( $rowData2 as $rowData2data ){

                    if ( $rowData2data[0] != '' ){

                        $get_staff    = $staff_all[$rowData2data[0]] ;
                        $staff_id     = $get_staff['staff_id'] ;
                        $staff_idno   = $get_staff['staff_idno'] ;

                        $point_amount = $rowData2data['1'] ;
                        $point_type   = ( $point_amount > 0 ? 'plus' : ( $point_amount < 0 ? 'minus' : '' ) ) ;
                        $remark       = $rowData2data['2'] ;

                        if ( $get_staff != null && $get_staff['branch_id'] == $_SESSION['url_get_branch_admin'] ){
                            
                            if ( ( $point_type == 'plus' || $point_type == 'minus' ) && ( $point_amount < 0 || $point_amount > 0 ) ){

                                $update_list[$point_type][$point_amount][$remark][] = $staff_id ;

                                $update_branchid  = $get_staff['branch_id'] ;

                            }else{
                                $error_type++ ;
                                $error_typelist[] = $point_type ;
                            }

                        }else{
                            $error_staff++ ;
                            $error_stafflist[] = $rowData2data[0] ;
                        }
                    }
                }


                if ( $error_staff == 0 ){
                    if ( $error_type == 0 ){



                        $array_setting_adjustment = [] ;
                        foreach ( [ 'plus', 'minus' ] as $k => $v ){

                            $select_setting = $mysqli->query( "SELECT adjustment_id FROM setting_adjustment
                                                               WHERE deleted_at IS NULL AND adjustment_site = 'system' AND adjustment_type = '".$v."' AND adjustment_mode = 'fixed' AND adjustment_scenario = 'import-point'" ) ;
                            if ( $select_setting->num_rows > 0 ){
                                $row_setting = $select_setting->fetch_assoc() ;
                                $array_setting_adjustment[$v] = $row_setting['adjustment_id'] ;
                            }else{
                                $mysqli->query( "INSERT INTO setting_adjustment
                                                 ( adjustment_site, adjustment_type, adjustment_mode ) VALUES
                                                 ( 'system', '".$v."', 'fixed' )" ) ;
                                $setting_adjustment_id        = $mysqli->insert_id ;
                                $array_setting_adjustment[$v] = $setting_adjustment_id ;

                                foreach ( $LANGS as $klang => $vlang ){
                                    $title        = 'System Import Point ( '.ucwords($v).' )' ;

                                    checkLangUpdate( 'setting_adjustment_translation', 'adjustment_id', $setting_adjustment_id, $klang, [ 
                                        'title'     => [ 'type' => 'input', 'value' => $title   ]
                                    ] ) ;
                                }

                            }
                        }

                        foreach ( $update_list as $ktype => $vtype ){
                            foreach ( $vtype as $kpoint => $vpoint ){
                                foreach ( $vpoint as $kremark => $vremark ){

                                    $setting_adjustment_id = $array_setting_adjustment[$ktype] ;

                                    if ( $mysqli->query( "INSERT INTO staff_adjustment
                                                          ( `adjustment_type`, `created_branch_id`, `created_by_userid`, `created_by`, `department_id`, `setting_adjustment_id`, `point`, `remark` ) VALUES
                                                          ( '".$ktype."', '".$update_branchid."', '".$_SESSION['system_id']."', '', '', '".$setting_adjustment_id."', '".$kpoint."', '".$kremark."' )" ) ){

                                        $adjustment_id  = $mysqli->insert_id ;
                                        $adjustment_so  = 'AD'.strPad( 6, $adjustment_id ) ;
                                        $mysqli->query( "UPDATE staff_adjustment SET adjustment_so = '".$adjustment_so."' WHERE adjustment_id = '".$adjustment_id."'" ) ;

                                        foreach ( $vremark as $kstaff => $vstaff ){
                                            $mysqli->query( "INSERT INTO staff_adjustment_point ( `adjustment_id`, `setting_adjustment_id`, `staff_id`, `point` ) VALUES ( '".$adjustment_id."', '".$setting_adjustment_id."', '".$vstaff."', '".$kpoint."' )" ) ;

                                            pointMovement( 'adjustment', $adjustment_id, $ktype, 'normal', $vstaff, $kpoint, $kremark ) ;
                                            pushToUserCron( 'staff_adjustment', $adjustment_id, $vstaff, 'Point Adjustment', $kremark ) ;
                                        }

                                    }

                                }
                            }
                        }

                        $redirect_url = '?result=success&msg=Import Successful' ;

                    }else{
                        $redirect_url = '?result=error&msg=Some of type invalid ( '.implode(', ', $error_typelist).' )' ;
                    }
                }else{
                    $redirect_url = '?result=error&msg=Some of the Staff not exists or invalid branch ( '.implode(', ', $error_stafflist).' )' ;
                }

            }

        }else{
            $redirect_url = '?result=error&msg=Failed to Import' ;
        }

        header( "Location: ".$redirect_url ) ;
        exit;
    }
}

$result = $_GET['result'];
$msg    = $_GET['msg'];
if ($result == 'error') {
    $display_error = '<div class="result_error">'.$msg.'</div>' ;
}elseif ($result  == 'success') {
    $display_error = '<div class="result_success">'.$msg.'</div>' ;
}

include 'requires/page_header.php';
include 'requires/page_top.php';
?>

<div class="warper container-fluid">
    <div class="page-header">
        <h1><?= $lang['Import'] ?> <small><?= $lang['Point'] ?></small></h1>
        <?= $display_error ?>
    </div>

    <?php if ( permissionCheck($row_user, 'import-point-upload') ){ ?>
        <div class="panel panel-default" id="basic-table-title">
            <div class="panel-heading">
                Import Excel File
                <a href="./samples/import-point.xlsx" download style="float:right;" >Download Sample</a>
            </div>
            <div class="panel-body">
                <form method="post" class="form-horizontal" style="max-width:600px;" enctype="multipart/form-data" novalidate="novalidate">
                    <div class="form-group">
                        <label class="col-sm-1 control-label"></label>
                        <div class="col-sm-10">
                            <input type="file" name="import-excel" class="file_button control-label" />
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-11">
                            <input type="hidden" name="page_mode" value="<?= $page_mode ?>" />
                            <button type="submit" class="btn btn-purple" style="float:right"><?= $lang['submit'] ?></button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    <?php } ?>

</div>



<?php

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