<?php
$must_login             = true ;
$require_path           = '../../../' ;
$require_sub            = '../../' ;
require( $require_path.'extensions/sms.php' ) ;
require( $require_path.'extensions/mailer.php' ) ;
require( $require_sub.'header.php' ) ;

if ( $boolean_login ){
    $status             = '300' ;

    $leave_type         = $array['leave_type'] ;
    $leave_fullhalf     = $array['leave_fullhalf'] ;
    $leave_from         = $array['leave_from'] ;
    $leave_to           = $array['leave_to'] ;
    $leave_reason       = $array['leave_reason'] ;

    $datetime1          = new DateTime($leave_from) ;
    $datetime2          = new DateTime($leave_to) ;
    $interval           = $datetime1->diff($datetime2) ;
    $days               = $interval->format('%a')+1 ;

    $photos             = $array['photos'] ;

    if ( $leave_fullhalf == 'half' ){
        $leave_to       = $leave_from ;
    }

    if ( $leave_type   != '' && $leave_from != '' && $leave_to != '' && $leave_reason != '' ){
        $status         = '274' ;

        $from           = $leave_from ;
        $to             = $leave_to ;

        if ( date('Y', strtotime($from)) == date('Y', strtotime($to)) ){
            $status              = '273' ;

            // get again staff 
            $department          = '' ;
            $get_department      = $mysqli->query("SELECT department_id FROM staff_department
                                                   WHERE deleted_at IS NULL AND staff_id = '".$staff_info['staff_id']."'") ;
            if ( $get_department->num_rows > 0 ){
                while ( $row_department = $get_department->fetch_assoc() ){
                    $department .= ',('.$row_department['department_id'].')' ;
                }
                $department      = substr($department, 1) ;
            }

            // get days
            $datetime1           = new DateTime($from) ;
            $datetime2           = new DateTime($to) ;
            $interval            = $datetime1->diff($datetime2) ;
            $days                = $interval->format('%a')+1 ;

            if ( $leave_fullhalf == 'half' ){
                $days            = '0.5' ;
            }

            $boolean_apply       = false ;

            // check left leave
            if ( $type             == 'unpaid' ){
                $boolean_apply      = true ;
            }else{

                $leave_days         = 0 ;
                $boolean_ded        = false ;

                // return leave to the staff
                $get_leave_year     = $mysqli->query("SELECT leave_days FROM staff_leave_year
                                                      WHERE deleted_at IS NULL AND staff_id = '".$staff_info['staff_id']."' AND leave_type = '".$leave_type."' AND leave_year_from >= '".TODAYDAY."' AND leave_year_to <= '".TODAYDAY."' LIMIT 1") ;
                if ( $get_leave_year->num_rows > 0 ){
                    $row_leave_year = $get_leave_year->fetch_assoc() ;
                    $leave_days     = $row_leave_year['leave_days'] ;
                    $boolean_ded    = true ;
                }

                if ( $leave_days    > 0 ){

                    // get currently apply pending leave
                    $get_leave_pending  = $mysqli->query("SELECT leave_from, leave_to, leave_day FROM staff_leave
                                                      WHERE deleted_at IS NULL AND staff_id = '".$staff_info['staff_id']."' AND leave_type = '".$leave_type."' AND leave_status = 'pending' AND leave_from LIKE '".date('Y', time())."-%'") ;
                    if ( $get_leave_pending->num_rows > 0 ){
                        
                        $array_leave_pending[] = [
                            'from'     => $leave_from,
                            'to'       => $leave_to,
                            'days'     => $days
                        ] ;

                        while ( $row_leave_pending = $get_leave_pending->fetch_assoc() ){
                            $array_leave_pending[] = [
                                'from' => $row_leave_pending['leave_from'],
                                'to'   => $row_leave_pending['leave_to'],
                                'days' => $row_leave_pending['leave_day']
                            ] ;
                        }

                        foreach ( $array_leave_pending as $kk => $vv ){

                            $new_date         = date('Y-m-d', strtotime($vv['leave_from'])) ;

                            // check if full day or half day
                            $day_fullhalf     = 'full' ;
                            $leave_day        = $vv['days'] ; // should change to $days
                            $cut_day          = '1' ;
                            if ( $leave_day  == '0.5' ){
                                $day_fullhalf = 'half' ;
                                $leave_day    = '1' ;
                                $cut_day      = '0.5' ;
                            }

                            // save to leave more
                            for ( $a = 1 ; $a <= $leave_day ; $a++ ){

                                $leave_type_mode     = 'working' ;
                                $leave_work_direct   = 'no' ;
                                $leave_work_day      = '0' ;
                                $boolean_holiday     = false ;
                                $boolean_off         = false ;

                                // check if today is holiday
                                $get_holiday         = $mysqli->query("SELECT * FROM $prefixSettingHoliday
                                                                       WHERE deleted_at IS NULL AND  holiday_date = '".$new_date."' LIMIT 1") ;
                                if ( $get_holiday->num_rows > 0 ){
                                    $leave_type_mode = 'holiday' ;
                                    $boolean_holiday = true ;
                                    $leave_work_day  = '1' ;
                                }

                                // check working days if today off
                                if ( !$boolean_holiday ){
                                    $new_week_day    = date('N', strtotime($new_date)) ;
                                    $get_working     = $mysqli->query("SELECT * FROM setting_working
                                                                       WHERE deleted_at IS NULL AND group_id = '".$row_staff['group_id']."' AND working_day = '".$new_week_day."' LIMIT 1") ;
                                    if ( $get_working->num_rows > 0 ){
                                        $row_working = $get_working->fetch_assoc() ;
                                        if ( $row_working['working_on'] == 'no' ){
                                            $leave_type_mode = 'off' ;
                                            $boolean_off     = true ;
                                            $leave_work_day  = '1' ;
                                        }
                                        $leave_work_direct   = $row_working['working_direct_day'] ;
                                        if ( $leave_work_direct == 'yes' ){
                                            $leave_work_day  = '0.5' ;
                                        }
                                    }

                                    if ( !$boolean_off ){
                                        $leave_work_day = $cut_day ;
                                    }

                                }

                                $new_date = date('Y-m-d', strtotime($new_date . '+1 days')) ;

                                if ( !$boolean_holiday && !$boolean_off ){
                                    $leave_days = ( $leave_days - $leave_work_day ) ;   
                                }

                            }

                        }

                    }

                }

                if ( $leave_days >= 0 ){
                    $boolean_apply = true ;
                }

            }



            if ( $boolean_apply ){

                $status    = '203' ;

                $error     = 0 ;
                $mysqli->autocommit( false ) ;

                try {

                    $incharge_status = 'confirmed' ;

                    // insert into leave
                    $mysqli->query( "INSERT INTO staff_leave
                                    ( staff_id, leave_department, leave_type, leave_from, leave_to, leave_day, leave_reason, leave_file, leave_incharge_status, leave_status ) VALUES
                                    ( '".$staff_info['staff_id']."', '".$department."', '".$leave_type."', '".$leave_from."', '".$leave_to."', '".$days."', '".$leave_reason."', '".$leave_file."', '".$incharge_status."', 'pending' )" ) ;
                    $last_id         = $mysqli->insert_id ;

                    if ( checkExists($photos) ){
                        foreach ( $photos as $k => $v ){
                            if ( $v['type']     == 'local' ){
                                $file_upload     = ( $v['file'] ) ;
                                $upload          = uploadImage( 'Leave', $last_id.'-'.$last_id, $file_upload ) ;
                                if ( $upload['status'] != '200' ){
                                    $count_upload++ ;
                                }else{
                                    $mysqli->query( "UPDATE staff_leave SET
                                                     leave_file     = '".$upload['data']['file_name']."'
                                                     WHERE leave_id = '".$last_id."'" ) ;
                                }
                            }
                        }
                    }

                    // get team leave
                    $l_content       = '' ;
                    $leave_q         = $mysqli->query("SELECT a.leave_day, a.leave_from, a.leave_to, a.leave_status, b.staff_name FROM staff_leave a
                                                       LEFT JOIN staff b ON ( a.staff_id = b.staff_id )
                                                       WHERE a.deleted_at IS NULL AND a.leave_id != '".$last_id."' AND a.leave_incharge_status = 'confirmed' AND a.leave_status != 'rejected' AND a.leave_from >= '".TODAYDAY."'
                                                       ORDER BY a.leave_from ASC") ;
                    if ( $leave_q->num_rows > 0 ){
                        while ( $leave = $leave_q->fetch_assoc() ){
                            $l_content .= '
                            <tr>
                                <td>'.$leave['staff_name'].'</td>
                                <td style="text-align:center;">'.$leave['leave_day'].'</td>
                                <td style="text-align:center;">'.$leave['leave_from'].' ~ '.$leave['leave_to'].'</td>
                                <td style="text-align:center;">'.ucwords($leave['leave_status']).'</td>
                            </tr>' ;
                        }
                    }else{
                        $l_content .= '<tr><td colspan="4">No leave found.</td></tr>' ;
                    }

                    // set date
                    $array_date = [ 
                        1 => 'Monday',  
                        2 => 'Tuesday',  
                        3 => 'Wednesday',  
                        4 => 'Thursday',  
                        5 => 'Friday',  
                        6 => 'Saturday',  
                        7 => 'Sunday',
                    ] ;
                    $leave_from_date         = $array_date[ date('N', strtotime($leave_from)) ] ;
                    $leave_to_date           = $array_date[ date('N', strtotime($leave_to)) ] ;

                    // get current annual leave or sick leave
                    $leave_year_days         = 0 ;
                    if ( $leave_type        != 'unpaid' ){
                        $leave_year_q        = $mysqli->query("SELECT leave_days FROM staff_leave_year
                                                               WHERE deleted_at IS NULL AND staff_id = '".$staff_info['staff_id']."' AND leave_type = '".$leave_type."' ORDER BY leave_year_id DESC LIMIT 1") ;
                        if ( $leave_year_q->num_rows > 0 ){
                            $leave_year      = $leave_year_q->fetch_assoc() ;
                            $leave_year_days = $leave_year['leave_days'] ;
                        }
                    }

                    pushToUserCron( 'staff_leave', $last_id, $staff_info['staff_id'], 'Apply Leave', 'Leave has been created.' ) ;

                    // send email when apply leave
                    $content = '
                    Hello Team, <br /><br />
                    Please approve <b>'.$staff_info['staff_name'].'</b> leave.<br /><br />
                    <b>'.$staff_info
                    ['staff_name'].'</b> has applied for <b>'.ucwords($leave_type).'</b> leave from <b>'.date('d/m/Y', strtotime($leave_from)).' ('.$leave_from_date.')</b> to <b>'.date('d/m/Y', strtotime($leave_to)).' ('.$leave_to_date.')</b> with the reason <b>('.$leave_reason.')</b>. Please review the application and appove or reject it.<br /><br />
                    '.( $leave_type != 'unpaid' ? 'If this application is approved, it will utilize <b>'.$days.' day(s)</b> and there is <b>'.($leave_year_days-$days).' day(s)</b> remaining <b>'.ucwords($leave_type).'</b> leave days.<br /><br />' : '' ).'
                    Currently, your team\'s leave schedule (nearby the date range) is illustrated as below:
                    <table width="600px">
                        <tr>
                            <th style="text-align:left;">Name</th>
                            <th>Day(s)</th>
                            <th>Date Range</th>
                            <th>Status</th>
                        </tr>
                        '.$l_content.'
                    </table><br /><br />
                    The approval for this application belongs to you, so do keep this e-mail safe.' ;

                    $mailer          = new Mailer() ;
                    $mailer->from    = EMAILNOREPLY ;
                    $mailer->to      = $EMAILCC ;
                    $mailer->cc      = [ $staff_info['staff_email'] ] ;
                    $mailer->subject = ucwords($leave_type).' leave request from '.$staff_info['staff_name'] ;
                    $mailer->body    = $content ;
                    $mailer->send() ;

                }catch( Exception $e ){
                    $message         = $e ;
                    $error++;
                }

                if( $error          == 0 ) {
                    $status          = '200' ;

                    // commit query
                    $mysqli->commit() ;

                }else{
                    $mysqli->rollback() ;
                }

            }
        }
    }
}

require( $require_sub.'footer.php' ) ;
?>