<?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-full-attendance-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-full-attendance' ;
$active_menu      = 'import-full-attendance' ;  

$date_time        = escapeString($_GET['date_time']) ;
$date_current     = TODAYDAY ;
$date_time        = ( $date_time != '' ? $date_time : date('Y-m', strtotime($date_current)) ) ;
$date_time_day    = $date_time.'-01' ;

$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) ){

            $update_branchid  = '' ;
            $error_stafflist  = [] ;
            $error_staff      = 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'] ;

                    if ( $get_staff != null && $get_staff['branch_id'] == $_SESSION['url_get_branch_admin'] ){

                        $atten_date  = fromExcelToLinux($atten_date) ;
                        
                        $update_list[] = $staff_id ;

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


            if ( $error_staff == 0 ){

                $mysqli->query( "DELETE FROM `staff_attendance_manual` WHERE branch_id = '".$_SESSION['url_get_branch_admin']."' AND attendance_date = '".$date_time_day."'" ) ;

                foreach ( $update_list as $kstaff => $vstaff ){
                    $mysqli->query( "INSERT INTO staff_attendance_manual 
                                  ( `branch_id`, `staff_id`, `attendance_date` ) VALUES 
                                  ( '".$_SESSION['url_get_branch_admin']."', '".$vstaff."', '".$date_time_day."' )" ) ;
                }

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

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

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

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


// select query
$mysqli_page   = $mysqli->query( "SELECT b.staff_idno, b.staff_name, a.updated_at FROM staff_attendance_manual a
                                  LEFT JOIN staff b ON ( a.staff_id = b.staff_id )
                                  WHERE a.branch_id = '".$_SESSION['url_get_branch_admin']."' AND a.attendance_date = '".$date_time_day."'" ) ;





$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';
?>

<style>
.datepicker_box{
    display: inline-block;
}
.select_datepicker{
    text-align: center;
}
</style>

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

    <div class="panel panel-default" id="basic-table-title">
        <div class="panel-heading">
            Import Excel File
            <a href="./samples/import-full-attendance.xlsx" download style="float:right;" >Download Sample</a>
        </div>
        <div class="panel-body">

            <div class="form-group">
                <div class="col-sm-12">

                    <div class="box-tools col-sm-12 col-md-12 col-lg-12" style="text-align: center; margin: 20px;">
                        <a href="?<?= $search_url ?>&page=1&date_time=<?= date('Y-m', strtotime($date_time.' -1 month')) ?>" class="width_auto"><?= $lang['Prev Month']?></a>

                        <div class="datepicker_box">
                            <span style="margin-left:10px; margin-right:10px;">
                                <input type="text" readonly name="date_time" class="select_datepicker" value="<?= $date_time ?>">
                            </span>
                        </div>

                        <?php
                        if ( $date_time >= date('Y-m', strtotime(TODAYDAY)) ){}else{
                            ?>
                            <a href="?<?= $search_url ?>&page=1&date_time=<?= date('Y-m', strtotime($date_time.' +1 month')) ?>" class="width_auto"><?= $lang['Next Month']?></a>
                            <?php
                        }
                        ?>
                    </div>

                </div>
            </div>

            <div>&nbsp;</div>
            <div>&nbsp;</div>

            <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">
                    <label class="col-sm-1 control-label"></label>
                    <div class="col-sm-10">
                        <input type="hidden" name="page_mode" value="<?= $page_mode ?>" />
                        <button type="submit" class="btn btn-purple"><?= $lang['submit'] ?></button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <div class="panel panel-default" id="basic-table-title">
        <div class="warper container-fluid">    
            <form method="post">
                <div class="panel panel-default">
                    <div class="panel-heading"></div>
                    <div class="panel-body">
                        <table cellpadding="0" cellspacing="0" border="0" class="responsive table table-striped table-bordered" id="basic-datatable">
                            <thead>
                                <tr>
                                    <th>Staff ID</th>
                                    <th>Name</th>
                                    <th>Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                if ($mysqli_page->num_rows > 0){
                                    while ($row_page = $mysqli_page->fetch_array(MYSQLI_ASSOC)){
                                        echo '
                                         <tr class="odd gradeX">
                                            <td>'.$row_page['staff_idno'].'</td>
                                            <td>'.$row_page['staff_name'].'</td>
                                            <td>'.resetDateFormat($row_page['updated_at']).'</td>
                                        </tr>';
                                    }
                                }else{
                                    echo '
                                    <tr class="odd gradeX">
                                        <td class="border_none">'.$lang['no_data'].' </td>
                                        <td class="border_none"></td>
                                        <td class="border_none"></td>
                                    </tr>' ;
                                }
                                ?>
                            </tbody>
                        </table>
                        <?= $page_pagination['page_pagination'] ?>
                    </div>
                </div>
            </form>
        </div>
    </div>

</div>



<?php

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