<?php


function display_batch_item_issue_select_details($dii_no, $view_only=false) { 
    global $Ajax, $daily_item_types_array;
    
    display_heading("Transaction Details");
    
    $trans_no = $type = -1;
    $header = get_batch_item_issue_header_record($dii_no);
    if (is_array($header)) {
        $trans_no = $header['trans_no'];
        $type = $header['type'];
    } 
    
    $Ajax->activate('nsit_details');
    div_start('nsit_details');
    
        start_table(TABLESTYLE, "width=98%");

            $th = array(_("Id"), _("Item Type"), _("Unit"), _("Tran Qty"), _('Item Cost'), 
                        _('Issuing To Employee'), _('Movement Type'), _('Person'), _('Job'), 
                        "", "", "", "");  

            $k = 0; //row colour counter
                $result = get_batch_item_issue_details($trans_no, $type);      
                    while ($row = db_fetch($result)) {
                        if ($row['daily_item_type'] == NSIT_NON_STOCK_ITEM || $row['daily_item_type'] == NSIT_STOCK_ITEM) {
                            $item_name = ($row["stock_id"]." - ".$row["item_description"]);  
                        } else {
                            $item_name = ($row["item_description"]);
                        }
                        table_section_title("Item : ".$item_name, "13 style=background-color:#0ec9ba; align:left");                        
                        table_header($th);
                        alt_table_row_color($k);

                            label_cell($row['id'], 'align=center');
                            label_cell($daily_item_types_array[$row['daily_item_type']]);
                            
                            label_cell($row["unit_name"]);
                            
                            $dec = get_qty_dec($row["stock_id"]);
                            label_cell(number_format($row["tran_qty"], $dec), 'align=right');
                            
//                            if ($row['daily_item_type'] == NSIT_COMMENT) {
//                                label_cell('No budget required');
//                            } else {
//                                label_cell($row["task_description"]);
//                            }
                            
                            $tran_unit_cost = $row["standard_cost"] * $row["conversion_factor"];
                            if ($tran_unit_cost > 0) {
                                label_cell(number_format($tran_unit_cost, $dec), 'align=right');
                            } else {
                                label_cell('');
                            }
                            
                            $employee_formatted_name = get_group_company_employee_formatted_long_name($row["employee_company_code"], $row["employee_code"]);
                            label_cell($employee_formatted_name);
                            
                            label_cell($row['movement_type_name']);
                            
                            $lf_name = get_movement_type_linked_field_values($row['linked_field_type'], $row['linked_field_id'], $row['group_company_code']);
                                label_cell($lf_name["value"]);          
                            
                            label_cell($row["site_description"]);          
//                            label_cell(nl2br($row["line_comment"]));       
                            
                            if($view_only){
                                label_cell("", "colspan=4");
                            }else{
                                label_cell(get_batch_item_issue_transactions_str(ST_PURCH_REQ, $row['id'], "PR"));
                                label_cell(get_batch_item_issue_transactions_str(ST_MATERIAL_REQ, $row['id'], "MR"));
                                label_cell(get_batch_item_issue_transactions_str(ST_DAILY_ITEM_ISSUE, $row['id'], "DII"));
                                button_cell("Refresh", _("Refresh"), false);
                            }
                            
                            if(strlen($row["line_comment"]) > 0){
                                alt_table_row_color($k);
                                label_cell("", "colspan=3");
                                label_cell(nl2br($row["line_comment"]), "colspan=6 align=right");          
                                label_cell("", "colspan=4");
                                end_row();   
                            }

                        end_row(); 
                        
                        start_row();
                        display_batch_item_issue_selected_transactions($row['id'], INFINITE_START_DATE, INFINITE_END_DATE);

                        end_row(); 
//                        br(1);

                    }

        end_table(1);
    
    div_end();
}


function can_process_batch_item_issue_transactions($biih)
{
    global $systypes_array;
    
    $batch_no = $biih['id'];
    
    if (!(is_date(sql2date($biih['tran_date'])))) 
    {
        $message = ( _("Entered date is not a valid date."));
        $set_focus = ('');
        return array("success"=>false, "set_focus"=>$set_focus, "message"=>$message);
    }
    
    if (!is_date_in_fiscalyear($biih['tran_date'],true)) {
        $message = (_("The entered date is not in fiscal year."));
        $set_focus = ('');
        return array("success"=>false, "set_focus"=>$set_focus, "message"=>$message);
    }
        
    $msg = is_accounting_period_open($biih['tran_date'],true);
    if ($msg['success'] !== true)
    {
        $message = ($msg['message']);
        $set_focus = ('');
        return array("success"=>false, "set_focus"=>$set_focus, "message"=>$message);
    }
            
    // BII header row_state
    if($_POST['biih_row_state'] != $biih['row_state']){
        $message = $systypes_array[ST_BATCH_ITEM_ISSUE]." #".$batch_no." has been modified. Please refresh the screen to see the updated details.";
        return array("success"=>false, "trans_no"=>$batch_no, "message"=>$message);
    }
    
    // BII header status
    if(!in_array($biih['approval_status'], array(AS_NEW, AS_AWAITING_APPROVAL, AS_WITH_THE_APPROVER, AS_REOPENED, AS_BACK_TO_ORIGINATOR))){
        $message = "Status of this ".$systypes_array[ST_BATCH_ITEM_ISSUE]." does not allow any updates.";
        return array("success"=>false, "trans_no"=>$batch_no, "message"=>$message);
    }
    
    // full quantity allocation
    $result = get_batch_item_issue_detail_records($biih['trans_no'], $biih['type']);
    while ($row = db_fetch($result)){
        $bii_line_id = $row['id'];
        $bii_line_qty = $row['qty'];
        $alloc_qty = get_batch_item_issue_detail_line_allocated_qty($bii_line_id);
        if(($bii_line_qty - $alloc_qty) > 0.00001){
            $message = "Detail line #".$bii_line_id." : Transactions not selected for the full quantity.";
            return array("success"=>false, "trans_no"=>$batch_no, "message"=>$message);
        }
        if(($alloc_qty - $bii_line_qty) > 0.00001){
            $message = "Detail line #".$bii_line_id." : some quantity over allocated.";
            return array("success"=>false, "trans_no"=>$batch_no, "message"=>$message);
        }
    }
    
    // task ids for all DII lines
    $result2 = get_batch_item_issue_detail_no_task_dii_records($biih['trans_no'], $biih['type']);
    while ($row2 = db_fetch($result2)){
        $biit_id = $row2['id'];
        $message = "Transaction line #".$biit_id." : No budget selected.";
        return array("success"=>false, "trans_no"=>$batch_no, "message"=>$message);        
    }
    
    return array("success"=>true, "trans_no"=>$batch_no, "message"=>"");
}


function process_batch_item_issue_transactions($type, $trans_no)
{
    $biih_row = get_batch_item_issue_header_record_type_trans_no($type, $trans_no);
    
    $pbii_prs_msg = process_batch_item_issue_prs($biih_row);
    if($pbii_prs_msg["success"] !== true){
        return $pbii_prs_msg;
    }
    
    $pbii_mrs_msg = process_batch_item_issue_mrs($biih_row);
    if($pbii_mrs_msg["success"] !== true){
        return $pbii_mrs_msg;
    }
    
    $pbii_diis_msg = process_batch_item_issue_diis($biih_row);
    if($pbii_diis_msg["success"] !== true){
        return $pbii_diis_msg;
    }
    
    return array("success"=>true, "trans_no"=>$trans_no, "message"=>"");
}

function close_batch_item_issue_source_transactions($type, $trans_no)
{
    $result = get_batch_item_issue_processed_source_transactions($type, $trans_no);
    while ($row = mysql_fetch_array($result)) {
        if($row['source_type_id'] == ST_PURCH_REQ){
            close_batch_item_issue_source_pr($row['source_type_no']);
        }elseif($row['source_type_id'] == ST_MATERIAL_REQ){    
            close_batch_item_issue_source_mr($row['source_type_no']);  
        }        
    }    
}


function get_batch_item_issue_created_target_transactions_string($type, $trans_no)
{
    global $systypes_array;
    
    $s = "";
    
    $result = get_batch_item_issue_processed_target_transactions($type, $trans_no);
    while ($row = mysql_fetch_array($result)) {
        if(strlen($s) > 0){
            $s .= ", ";
            $s .= "<br>";
        }
        $s .= $systypes_array[$row['target_type_id']]." #".$row['target_type_no'];      
    }  
    
    return $s;
}

function handle_process_batch_item_issue_transactions($batch_no)
{    
    global $systypes_array;    
    
    
    $biih = get_batch_item_issue_header($batch_no); 
    $type = $biih['type'];
    $trans_no = $biih['trans_no'];
        
    begin_transaction();
    
    $pbii_msg = process_batch_item_issue($biih);
    if($pbii_msg["success"] !== true){
        cancel_transaction();
        return $pbii_msg;
    }
    
    commit_transaction();
    
    close_batch_item_issue_source_transactions($type, $trans_no);
    
    $s = get_batch_item_issue_created_target_transactions_string($type, $trans_no);
    
    $message = $systypes_array[$type]." #".$trans_no." has been processed.";
    $message .= "<br>".$s." created.";
    return array("success" => true, 'trans_no' => $trans_no, "message" => $message);
    
    
}


function check_batch_item_issue_all_transactions_processed($type, $trans_no)
{
    $s = "";
    
    $result = get_batch_item_issue_not_processed_transactions($type, $trans_no);
    while ($row = mysql_fetch_array($result)) {
        if(strlen($s) > 0){
            $s .= ", "; 
        }
        $s .= $row['id'];      
    }  
    
    if($s != ""){
        $message = "Could not process transaction line Nos ".$s;
        return array("success"=>false, "trans_no"=>$trans_no, "message"=>$message);
    }else{
        return array("success"=>true, "trans_no"=>$trans_no, "message"=>"");
        
    }
    
}


function process_batch_item_issue($biih)
{
    $type = $biih['type'];
    $trans_no = $biih['trans_no'];
    $row_state = $biih['row_state'];
    
    $hpbiit_msg = can_process_batch_item_issue_transactions($biih);
    if($hpbiit_msg["success"] !== true){
        return $hpbiit_msg;
    }
    
    $pbiit_msg = process_batch_item_issue_transactions($type, $trans_no);
    if($pbiit_msg["success"] !== true){
        return $pbiit_msg;
    }
    
    $cap_msg = check_batch_item_issue_all_transactions_processed($type, $trans_no);
    if($cap_msg["success"] !== true){
        return $cap_msg;
    }
    
    $urs_msg = update_batch_item_issue_processed($type, $trans_no, $row_state);
    if ($urs_msg['success'] !== true) {
        return array("success" => false, 'trans_no' => $trans_no, "message" => $urs_msg['message']);
    }
        
    return array("success" => true, 'trans_no' => $trans_no, "message" => "");
    
}
