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

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

    $task_id            = $array['task_id'] ;
    $reason             = $array['reason'] ;

    if ( $task_id != '' && $reason != '' ){
        $status         = '201' ;

        $select = $mysqli->query( "SELECT * FROM task a
                                   WHERE a.deleted_at IS NULL AND a.task_id = '".$task_id."' AND ( a.created_by = '".$staff_info['staff_id']."' OR a.assigned_by = '".$staff_info['staff_id']."' OR EXISTS ( SELECT b.staff_id FROM task_joinstaff b WHERE a.task_id = b.task_id AND b.staff_id = '".$staff_info['staff_id']."' LIMIT 1 ) ) AND a.status IN ( 'pending', 'assigned', 'completed', 'confirmed' ) LIMIT 1" ) ;
        if ( $select->num_rows > 0 ){
            $status              = '303' ;

            $row                 = $select->fetch_assoc() ;

            $update_status       = '' ;
            if ( $row['status'] == 'confirmed' ){
                if ( $row['created_by'] == $staff_info['staff_id'] ){
                    $update_status   = 'resubmit' ;
                }
            }else{
                $update_status   = 'rejected' ;
            }

            if ( $update_status != '' ){
                $status          = '202' ;

                if ( $mysqli->query( "UPDATE task SET
                                      todo_done       = '0',
                                      status          = '".$update_status."'
                                      WHERE task_id   = '".$task_id."'" ) ) {

                    $mysqli->query( "INSERT INTO task_rejected 
                                     ( `task_id`, `staff_id`, `remark` ) VALUES
                                     ( '".$task_id."', '".$staff_info['staff_id']."', '".$reason."' )" ) ;

                    if ( $update_status == 'resubmit' ){
                        $mysqli->query( "UPDATE task_todo SET
                                         is_done       = 'no'
                                         WHERE task_id = '".$task_id."'" ) ;
                    }

                    $status = '200' ;

                    // push to notification
                    $related_staffid = getTaskRelatedStaff( $task_id, $row['created_by'], $row['assigned_by'] ) ;
                    foreach ( $related_staffid as $k => $v ){
                        pushToUserCron( 'task', $task_id, $v, 'Task Rejected', 'Task ( '.$row['task_so'].' ) has been rejected' ) ;
                    }
                }
            }

        }

    }
}

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