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

$custom_message          = '' ;

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

    $advance_amount      = $array['advance_amount'] ;
    $advance_reason      = $array['advance_reason'] ;
    $advance_paidby      = $array['advance_paidby'] ;

    if ( $advance_amount != '' && $advance_reason != '' && $advance_paidby != '' ){
        $status          = '305' ;

        $day             = date('j', strtotime(TODAYDATE)) ;

        // check query exsits
        $setting_query   = $mysqli->query("SELECT post_id, post_title as advance_from, post_link as advance_to, post_content as advance_remark FROM system_post
                                           WHERE post_type = 'page-advance' AND post_categories = 'page-advance' AND post_trash = '0' LIMIT 1") ;
        if ( $setting_query->num_rows > 0 ){
            $setting     = $setting_query->fetch_assoc() ;
        }

        $boolean_advance = false ;
        if ( $setting['advance_from'] != '' ){
            if ( $setting['advance_from'] <= $day && $setting['advance_to'] >= $day ){
                $boolean_advance = true ;
            }else{
                $status          = '399' ;
                $custom_message  = $setting['advance_remark'] ;
            }
        }else{
            $boolean_advance = true ;
        }

        if ( $boolean_advance ){

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

            try {

                $advance_amount = is_numeric($advance_amount) ? number_format($advance_amount, 2, '.', '') : 0 ;
                $advance_reason = ( $advance_reason != '' ? $advance_reason : 'ADVANCE' ) ;

                // insert into advance
                $mysqli->query("INSERT INTO staff_advance
                                ( staff_id, advance_paidby, advance_amount, advance_reason, advance_status ) VALUES
                                ( '".$staff_info['staff_id']."', '".$advance_paidby."', '".$advance_amount."', '".$advance_reason."', 'pending' )" ) ;

                $staff_advance_id = $mysqli->insert_id ;

                pushToUserCron( 'staff_advance', $staff_advance_id, $staff_info['staff_id'], 'Apply Advance', 'Advance has been created.' ) ;

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

            if( $error == 0 ) {

                $status  = '200' ;

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

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

        }
    }
}

$data['custom_message'] = $custom_message ;

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