<?php
include "include/db.php";
include "include/auth.php";
if($user_type == 'admin'){
    $active_user_id = "admin_id = $admin_id,";
}elseif($user_type == 'staff'){
    $active_user_id = "employee_id = $employee_id,";
}

if(isset($_REQUEST['vendor_id']) && isset($_REQUEST['bid_item_id'])){

    if(strlen($_REQUEST['vendor_id']) >0 && strlen($_REQUEST['bid_item_id']) >0){
        $bid_item_id = $_REQUEST['bid_item_id'];
        $vendor_id = $_REQUEST['vendor_id'];
        $query_fetch_vendor = "SELECT * FROM vendor WHERE vendor_id = $vendor_id";
        $run_fetch_vendor = mysqli_query($conn, $query_fetch_vendor);
        if(mysqli_num_rows($run_fetch_vendor) == 1){
            $row_fetch_vendor = mysqli_fetch_array($run_fetch_vendor);
        }
        $vendor_name = $row_fetch_vendor['vendor_name'];

        $query_check2_bid_item = "SELECT * FROM bid_item WHERE bid_item_id = $bid_item_id"; 
        $run_check2_bid_item = mysqli_query($conn, $query_check2_bid_item);
        $row_check2_bid_item = mysqli_fetch_array($run_check2_bid_item);
        $wo_no = $row_check2_bid_item['bid_id'];
        $maps_id = $row_check2_bid_item['maps_id'];
        $query_fetch_maps_amount = "SELECT * FROM maps WHERE maps_id = $maps_id";
        $run_fetch_maps_amount = mysqli_query($conn, $query_fetch_maps_amount);
        if(mysqli_num_rows($run_fetch_maps_amount) ==1){
            while($row_fetch_maps_amount = mysqli_fetch_array($run_fetch_maps_amount)){
                $invoice_maps_name = $row_fetch_maps_amount['maps_name'];               
            }
        }
        
        $set_vendor_name_query = "UPDATE bid_item SET vendor_id = $vendor_id WHERE bid_item_id = $bid_item_id AND is_delete IS NULL";
        $set_vendor_name_run = mysqli_query($conn, $set_vendor_name_query);
        if($set_vendor_name_run){
            $time = date("Y-m-d H:i:s");

            $query_insert_log = "INSERT INTO change_log SET $active_user_id change_text = 'Added Vendor $vendor_name to item $invoice_maps_name', type = 'bid', item_id = $wo_no, time = '$time'"; 

            $run_insert_log = mysqli_query($conn, $query_insert_log);
            http_response_code(200);
            exit;
        }


    }else{
        http_response_code(400);
        exit;
    }    
}else{
   
    http_response_code(400);
    exit;
}
?>

