<?php

function check_total_lot_allocations_item_qty_exceed_allowable_qty($data_array=array(), $only_exceeded=true) {
    $type = $data_array['type'];
    $trans_no = $data_array['trans_no'];
    $ref_line_id = $data_array['line_id'];
    $stock_id = $data_array['stock_id'];
    $loc_code = $data_array['loc_code'];
    $parent_conversion_factor = $data_array['conversion_factor'];
    $parent_tran_qty = (float) $data_array['tran_qty'];
    $line_name = isset($data_array['line_name']) ? $data_array['line_name'] : 'Issue';
    $dec = 4; // get_qty_dec($stock_id);
    
    $total_lot_allocated_base_qty = (float) get_lot_allocations_total_qty($type, $trans_no, $ref_line_id, $stock_id, $loc_code);
    
        $total_lot_allocated_tran_qty = round(abs($total_lot_allocated_base_qty) / $parent_conversion_factor, $dec);

        if (round($total_lot_allocated_tran_qty, $dec) > round($parent_tran_qty, $dec)) {
            $diff = round($total_lot_allocated_tran_qty - $parent_tran_qty, $dec);
            
            return array("success" => false, 
                         "message" => "$line_name Line #$ref_line_id : Excess lot allocation. $line_name qty is $parent_tran_qty. Lot allocation is "
                                    . "$total_lot_allocated_tran_qty. Please deallocate $diff quantity in lots.", 
                         "alloc_qty" => $total_lot_allocated_tran_qty, "exceeded" => true);  
        } 
        
        if ($only_exceeded === false) { 
            if (round($parent_tran_qty, $dec) > round($total_lot_allocated_tran_qty, $dec)) {
                $diff = round($parent_tran_qty - $total_lot_allocated_tran_qty, $dec);
                
                return array("success" => false, 
                             "message" => "$line_name Line #$ref_line_id : Insufficient lot allocation. $line_name qty is $parent_tran_qty. Lot allocation is "
                                        . "$total_lot_allocated_tran_qty. Please allocate $diff more quantity in lots.", 
                             "alloc_qty" => $total_lot_allocated_tran_qty, "exceeded" => false);  
            }
        } 
        
        return array("success" => true, "message" => "");  
}

function create_all_lots_with_locations_from_lot_moves_and_lot_allocations() {
    $result = get_unique_lots_with_locations_from_lot_moves();
        while ($row = db_fetch($result)) {
            $msg = calculate_and_update_lot_balance_used_and_allocated_qty($row['lot_id'], $row['loc_code']);
                if ($msg['success'] === false) {
                    return $msg;
                }
        }
    
    $result_2 = get_unique_lots_with_locations_from_lot_allocations();
        while ($row = db_fetch($result_2)) {
            $msg = calculate_and_update_lot_balance_used_and_allocated_qty($row['lot_id'], $row['loc_code']);
                if ($msg['success'] === false) {
                    return $msg;
                }
        }
        
        return array('success' => true, 'message' => "All_lots_with_locations_from_lot_moves_and_lot_allocations have been created.");
}

function calculate_and_update_lot_balance_used_and_allocated_qty($lot_id, $loc_code) {
    $used_qty = get_location_lot_remain_total_in_base_qty($lot_id, $loc_code);
    
    $allocated_qty = get_lot_allocations_total_qty(lot_id: $lot_id, loc_code: $loc_code);
    
    return save_lot_balance($lot_id, $loc_code, $used_qty, $allocated_qty);
}

function save_lot_balance($lot_id, $loc_code, $used_qty, $allocated_qty) {
    $lot_row = get_lot_details($lot_id);
        if (! is_array($lot_row)) {
            return array('success' => false, 'message' => "Another user has deleted Lot #$lot_id.");
        }
        
    $lot_name = $lot_row['lot_reference'];
    $stock_id = $lot_row['stock_id'];
    $loc_name = get_location_name($loc_code);
    
    $lot_bal_row = get_lot_balance_records_by_filters(lot_id: $lot_id, loc_code: $loc_code, fetch: true);
    
        if (is_array($lot_bal_row)) {
            $af_row = update_lot_balance($lot_bal_row['tran_id'], $used_qty, $allocated_qty, $lot_bal_row['row_state']);
                if ($af_row != 1) {
                    return array('success' => false, 'message' => "Could not update Lot Balance Lot: $lot_name in Location: $loc_name.");
                }
        } else {
            $insert_id = insert_lot_balance($lot_id, $loc_code, $stock_id, $used_qty, $allocated_qty);
                if (! ($insert_id > 0)) {
                    return array('success' => false, 'message' => "Could not Add New Lot Balance record of Lot: $lot_name in Location: $loc_name.");
                }
        }
        
        return array('success' => true, 'message' => "Lot: $lot_name in Location: $loc_name Lot Balance has been saved.");
}

function lot_allocations_to_lot_moves($type, $trans_no, $ref_line_id=0, $transfer_from_loc_code=null) {
    global $systypes_array;
    
    $lot_loc_array = array();
    
    $result = get_lot_allocation_records($type, $trans_no, $ref_line_id);
        if (! (db_num_rows($result) > 0)) {
            return array('success' => false, 'message' => "No any Lot Allocation records found for ".$systypes_array[$type]." Trans #$trans_no.");
        }
        
        while ($row = db_fetch($result)) {
            $lot_alloc_id = $row['tran_id'];
            $ref_line_id = $row['ref_line_id'];
            
            if ($transfer_from_loc_code !== null) {
                $afr_2 = add_lot_move($row['tran_no'], $row['reference'], $row['lot_id'], $row['stock_id'], sql2date($row['tran_date']), -1*$row['qty'], 
                                      $row['type'], $transfer_from_loc_code, $row['tran_unit'], -1*$row['tran_qty'], $row['conversion_factor'], 
                                      $ref_line_id, $row['cost'], $row['source_type'], $row['source_trans_no'], $row['source_line_id']);

                if (! ($afr_2 > 0)) {
                    return array('success' => false, 'message' => $systypes_array[$type]." Detail Line #$ref_line_id could not make a Lot Move.");
                }
                
                $lot_loc_array[$row['lot_id']][$transfer_from_loc_code] = $row['lot_id'];
            }
            
            $afr = add_lot_move($row['tran_no'], $row['reference'], $row['lot_id'], $row['stock_id'], sql2date($row['tran_date']), $row['qty'], 
                                $row['type'], $row['loc_code'], $row['tran_unit'], $row['tran_qty'], $row['conversion_factor'], $ref_line_id, 
                                $row['cost'], $row['source_type'], $row['source_trans_no'], $row['source_line_id']);
            
            if (! ($afr > 0)) {
                return array('success' => false, 'message' => $systypes_array[$type]." Detail Line #$ref_line_id could not make a Lot Move.");
            }
            
            $del_af = delete_lot_allocation_line_by_id($lot_alloc_id);
                if (! ($del_af == 1)) {
                    return array('success' => false, 'message' => "Could not delete Lot Allocation Line #$lot_alloc_id.");
                }
                
                $lot_loc_array[$row['lot_id']][$row['loc_code']] = $row['lot_id'];
        }
        
        return array('success' => true, 'message' => "", "lot_loc_array" => $lot_loc_array);
}

function save_lot_balances($type, $trans_no) {
    $result = get_unique_lots_with_locations_from_lot_allocations($type, $trans_no);
        while ($row = db_fetch($result)) {
            $msg = calculate_and_update_lot_balance_used_and_allocated_qty($row['lot_id'], $row['loc_code']);
                if ($msg['success'] === false) {
                    return $msg;
                }
        }
        
        return array('success' => true, 'message' => "Lot balances have been saved.");
}

function save_lot_balances_from_array($lot_loc_array) {
    foreach ($lot_loc_array as $lot_id => $loc_array) {
        foreach ($loc_array as $loc_code => $val) {
            $msg = calculate_and_update_lot_balance_used_and_allocated_qty($lot_id, $loc_code);
                if ($msg['success'] === false) {
                    return $msg;
                }
        }
    }
        
        return array('success' => true, 'message' => "Lot balances have been saved.");
}
    
?>