<?php

function display_asset_transfer_receipt_header($asset_req_trn_id) {
    global $Refs;
    $atr_header = get_asset_requisition_transfer_with_asset_transfer_request_header_by_art_no($asset_req_trn_id);

    start_outer_table(TABLESTYLE2, "width=60%"); // outer table
        start_table(TABLESTYLE2);  
            table_section(1, "70%");

                $asset_req_trn_link = get_asset_trans_view_str(ST_ASSET_REQUISITION_TRANSFER, $atr_header['trans_no']);
                label_row("Issue:", $asset_req_trn_link);               
                text_row("Reference:", 'reference', $Refs->get_next(ST_ASSET_TRANSFER_RECEIPT), null, null);   
                label_row("From Project:", $atr_header['from_project_description']);   
                label_row("To Project:", $atr_header['to_project_description']);                       
                
                $asset_loc_row = get_asset_location($atr_header['art_to_asset_location']);
                label_row("From Location:", $asset_loc_row['location_name']);
                hidden("from_asset_location", $atr_header['art_to_asset_location']);   
                
                if (! isset($_POST['to_asset_location'])) {
                    $_POST['to_asset_location'] = $atr_header['atr_to_asset_location'];
                }
                asset_locations_list_row("To Location:", 'to_asset_location', null, 'Select To Asset Location', false); 
                

            table_section(2, "30%");
                $asset_req_link = get_asset_trans_view_str(ST_ASSET_TRANSFER_REQUEST, $atr_header['id']);
                label_row("Requesition:", $asset_req_link);               
                date_row("Date:", "tran_date");
                group_companies_list_row("Company:", 'company_code', null, false, true);
                group_company_employees_simple_list_row("Employee:", 'employee_code', $_POST['company_code'], null, "");
                textarea_row("Comment:", 'comment', null, 40, 3); 

                hidden('from_project_id', $atr_header['from_project_id']);
                hidden('to_project_id', $atr_header['to_project_id']);
                
        end_table();
    end_outer_table(2); // outer table
}

function display_asset_transfer_receipt_details($asset_req_trn_id) {      
    display_heading("Asset Transfer Receipt Details");
    br();
                              
    start_table(TABLESTYLE, "width=98%");
    $th = array(_("ID"), _("Asset"), _('From Site'), _('To Site'), _("Req. Comment"), _("Value"), _("Transferred. Qty"), _("Received. Qty"), 
                _("Quantity"), _("Comment"), _("Line Total"), "");                     

    table_header($th);
        $k = $line_total = 0;
            
        $result = get_asset_requisition_transfer_details_with_asset_transfer_receipt_count(0, $asset_req_trn_id);      
            while($myrow = db_fetch($result)) {
                alt_table_row_color($k);

                    label_cell($myrow['id'], "align=center");
                    label_cell($myrow["asset_code"]."-".$myrow["asset_description"]."-"."(".$myrow["asset_id"].")");  
                    label_cell($myrow["from_site_description"]);          
                    label_cell($myrow["to_site_description"]);          
                    label_cell($myrow["line_comment"]);
                    amount_decimal_cell($myrow["asset_value"]);

                    amount_cell($myrow["requisted_qty"]);
                    amount_cell($myrow["received_qty"]);
                    if(!(isset($_POST["this_quantity_".$myrow['id']]) && $_POST["this_quantity_".$myrow['id']] > 0)){
                        $_POST["this_quantity_".$myrow['id']] = ($myrow["requisted_qty"] - $myrow["received_qty"]);
                    }

                    if($myrow['requisted_qty'] > $myrow["received_qty"]){
                        amount_cells("", "this_quantity_".$myrow['id'], null, null, null, 0);
                        text_cells("", "at_line_comment_".$myrow['id'], null, 50);
                    }else{
                        label_cell("");
                        label_cell("");
                    }

                    if(isset($_POST["selected_".$myrow["id"]]) && $_POST["selected_".$myrow["id"]] > 0){
                        $line_cost = $myrow["asset_value"] * $_POST["this_quantity_".$myrow['id']];
                    }else{
                        $line_cost = 0;
                    }

                    amount_decimal_cell($line_cost);

                    if($myrow['requisted_qty'] > $myrow["received_qty"]){
                        check_cells("", "selected_".$myrow["id"], null, false, false, "align=center");    
                    }else{
                        label_cell("");
                    }

                end_row();

                $line_total += $line_cost;
            }    
       
        start_row();
            label_cell("Total:", "colspan=10 align=right");
            amount_cell($line_total, true); 
        end_row();  

    end_table(1);
    
    hidden("lines_total", $line_total);
}

function can_process_asset_transfer_receipt_header_and_line($asset_req_trn_id){  
    $msg = can_process_asset_transfer_receipt_header($asset_req_trn_id);
        if ($msg['success'] !== true) {
            if (isset($msg["focus_to"])) {
                set_focus($msg["focus_to"]);            
            }
            
            return $msg;
        }

    $msg2 = can_process_asset_transfer_receipt_lines($asset_req_trn_id);
        if ($msg2['success'] !== true) {
            if (isset($msg2["focus_to"])) {
                set_focus($msg2["focus_to"]);            
            }
            
            return $msg2;
        }

    return array("success" => true, "message" => "", "row_state" => $msg['row_state']);
}

function can_process_asset_transfer_receipt_header($asset_req_trn_id){  
    global $Refs;
//    $atr_header["row_state"] = null; 
    
    $atr_header = get_asset_transfer_header_record($asset_req_trn_id);
        if ($atr_header['approval_status'] == AS_COMPLETED) {
            $message = ("This Asset Requisition Transfer record #$asset_req_trn_id is alraedy completed.");
            return array("success" => false, "focus_to" => '', "message" => $message);      
        }

    if(!$Refs->is_valid($_POST['reference'])){
        $message = ("Please enter a reference.");
        $set_focus = 'reference';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);      
    }    
 
    $ref_msg = reference_exists($_POST['reference'], ST_ASSET_TRANSFER_RECEIPT, 0);
    if($ref_msg){
        $message = $ref_msg;
        $set_focus = 'reference';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);       
    }

    if(!is_date($_POST['tran_date'])){
        $message = "Date entered is not a valid date.";
        $set_focus = 'tran_date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }
    
    if(!(strlen($_POST['company_code']) > 0)){
        $message = "Please select a company.";
        $set_focus = 'company_code';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }
    
    if(!(strlen($_POST['employee_code']) > 0)){
        $message = "Please select an employee.";
        $set_focus = 'employee_code';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }

    if ($_POST['from_asset_location'] == $_POST['to_asset_location']) {
        $message = "To location cannot be same as From location.";
        $set_focus = 'to_asset_location';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    return array("success" => true, "message" => "", "row_state" => $atr_header['row_state']);    
}

function can_process_asset_transfer_receipt_lines($asset_req_trn_id){
    $slected_any_row = false;
    
    $result = get_asset_requisition_transfer_details_with_asset_transfer_receipt_count(0, $asset_req_trn_id);
        while ($row = db_fetch($result)) {
            if (isset($_POST["selected_".$row["id"]]) && $_POST["selected_".$row["id"]] == true) {
                if ($row['requisted_qty'] < ($row['received_qty'] + input_num("this_quantity_".$row['id']))) {
                    $message = "(Quantity + Received Quantity) should be smaller than or equal to Requested Quantity Line #".$row["id"];
                    $set_focus = "this_quantity_".$row['id'];
                    return array("success" => false, "focus_to" => $set_focus, "message" => $message);
                }
                
                $slected_any_row = true;
            }
        }
    
    if ($slected_any_row !== true) {
        $message = "At least one line should be selected before proccessing.";
        return array("success" => false, "focus_to" => '', "message" => $message);        
    }

    return array("success" => true, "focus_to" => '', "message" => "");  
}

function save_asset_transfer_receipt(&$asset_req_trn_id, $row_state) {
    $msg = save_asset_requisition_transfer_header($asset_req_trn_id);
        if($msg["success"] !== true){
            return $msg;
        }
        
    $trans_type = $msg['trans_type'];
    $trans_no = $msg['trans_no'];
    $at_id = $msg['at_id'];
    
    $result = get_asset_requisition_transfer_details_with_asset_transfer_receipt_count(0, $asset_req_trn_id);
        while($row = db_fetch($result)) {
            if (isset($_POST["selected_".$row["id"]]) && $_POST["selected_".$row["id"]] == true) {
                
                if($row['requisted_qty'] < ($row['received_qty'] + input_num("this_quantity_".$row['id']))){
                    return array("success" => false, 'atr_line_id' => $row["id"], "focus_to" => "this_quantity_".$row['id'], 
                                 "message" => "Another user has changed quatity.");
                }
                
                $from_site_id = $row['from_site_id'];
                $to_site_id = $row['to_site_id'];
                $asset_value = $row['asset_value'];
                $asset_id = $row['asset_id'];

                $issue_qty = input_num("this_quantity_".$row['id']);
                $aatl_msg = add_asset_transfer_line($at_id, $row["id"], $asset_id, $issue_qty, $asset_value, $_POST["at_line_comment_".$row['id']], 
                                                    $trans_type, $trans_no, $from_site_id, $to_site_id); 

                if ($aatl_msg['success'] !== true) {
                    return array("success" => false, 'at_id' => $at_id, "message" => $aatl_msg['message']);
                }

                $asset_tarnsfer_receipt_line_id = $aatl_msg['at_line_id'];
                
                $msg = update_asset_requisition_transfer_detail_line_total($row["id"], $row['row_state'], $trans_type);
                    if ($msg['success'] !== true) {
                        return $msg;
                    }

                add_asset_move($trans_type, $trans_no, $asset_tarnsfer_receipt_line_id, $_POST['reference'], $_POST['tran_date'], $asset_id, 
                               $_POST['from_asset_location'], $from_site_id, 0, -$issue_qty, $_POST['from_project_id'], $asset_value);

                add_asset_move($trans_type, $trans_no, $asset_tarnsfer_receipt_line_id, $_POST['reference'], $_POST['tran_date'], $asset_id, 
                               $_POST['to_asset_location'], $to_site_id, 0, $issue_qty, $_POST['to_project_id'], $asset_value);
            }
        }
        
        $msg = update_asset_transfer_header_total($at_id);
            if ($msg['success'] !== true) {
                return $msg;
            }
    
    if (check_all_asset_requisition_transfer_lines_fully_transferred($asset_req_trn_id)) {
        $msg = direct_update_document_status(ST_ASSET_TRANSFER, $asset_req_trn_id, AS_COMPLETED, $row_state);
            if ($msg['success'] !== true) {
                return $msg;
            }
    } else {
        $nm_af_rows = update_asset_transfer_row_status($asset_req_trn_id, $row_state);
            if ($nm_af_rows != 1) {
                return array("success" => false, "message" => "Could not update Asset Requisition Transfer row status. Another person already updated.");
            }
    }

    return array("success" => true, 'at_id' => $at_id, "message" => "Asset Transfer #$asset_req_trn_id has been proceed.");
}

function save_asset_requisition_transfer_header(&$asset_req_trn_id) {  
    $trans_type = ST_ASSET_TRANSFER_RECEIPT;
    $trans_no = get_next_trans_no($trans_type);
    
    $row = get_asset_requisition_transfer_with_asset_transfer_request_header_by_art_no($asset_req_trn_id);
    
    $from_project_id = $row['from_project_id'];
    $to_project_id = $row['to_project_id'];
    $from_asset_location = $row['art_to_asset_location'];
    $to_asset_location = $_POST['to_asset_location'];
    
    $msg = write_asset_transfer_header($asset_req_trn_id, $_POST['reference'], $_POST['company_code'], $_POST['employee_code'], $_POST['tran_date'], 
                                       $_POST['comment'], $_POST['lines_total'], $trans_type, $trans_no, 0, $from_project_id, 
                                       $to_project_id, $from_asset_location, $to_asset_location); 
    
        return $msg;
}

?>