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

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

    $search_query      = '' ;
    $search_query     .= " AND a.request_id = '".$array['request_id']."' AND a.staff_id = '".$staff_info['staff_id']."'" ;

    $query             = "SELECT * FROM request a
                          WHERE a.deleted_at IS NULL " . $search_query ;
    $mysqli_query      = $mysqli->query( $query ) ;

    if ( $mysqli_query->num_rows > 0 ){
        $status        = '299' ;

        $row           = $mysqli_query->fetch_assoc() ; 

        if ( $row['status'] == 'awaiting-collection' ){

            $status    = '200' ;

            $mysqli->query( "UPDATE request SET
                             status           = 'confirmed'
                             WHERE request_id = '".$array['request_id']."'" ) ;

            // get last movment
            $updateremark      = 'Stock deduct from so number ' . $row['request_so'] ;
            $updatequantity    = -($row['quantity']) ;

            if ( ( $updatequantity < 0 || $updatequantity > 0) && $updatequantity != '' ){
                $before        = 0 ;

                $main_id       = $row['main_id'] ;
                $sub_id        = $row['sub_id'] ;
                if ( $sub_id   > 0 ){
                    $main_id   = 0 ;
                }

                // get last movment
                $mysqli_select = $mysqli->query( "SELECT balance FROM setting_request_movement 
                                                  WHERE deleted_at IS NULL AND main_id = '".$main_id."' AND sub_id = '".$sub_id."'
                                                  ORDER BY movement_id DESC
                                                  LIMIT 1" ) ;
                if ( $mysqli_select->num_rows > 0 ){
                    $row_select = $mysqli_select->fetch_assoc() ;
                    $before     = $row_select['balance'] ;
                }

                $quantity       = $updatequantity ;
                $balance        = ( $before + $quantity ) ;

                $mysqli->query( "INSERT INTO setting_request_movement
                                 ( main_id, sub_id, before_quantity, quantity, balance, remark ) VALUES
                                 ( '".$main_id."', '".$sub_id."', '".$before."', '".$quantity."', '".$balance."', '".$updateremark."' )" ) ;
            }


        }
    }
}

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