<?php
/**********************************************************************
***********************************************************************/

$page_security = 'SA_TOOL_RETURN';
if (!@$_GET['popup'])
	$path_to_root = "..";
else	
	$path_to_root = "../..";

include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/inventory.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/includes/approval_functions.inc");
include_once($path_to_root . "/reporting/includes/reporting.inc");
include_once($path_to_root . "/projects/includes/db/project_boq_items_db.inc"); 
include_once($path_to_root . "/includes/common_functions.inc");
include_once($path_to_root . "/taxes/db/tax_groups_db.inc");
include_once($path_to_root . "/assets/includes/db/tool_returns_db.inc");
include_once($path_to_root . "/includes/ui/ui_lists_group_companies.inc");
include_once($path_to_root . "/includes/db/group_companies_db.inc");
include_once($path_to_root . "/assets/includes/db/tool_issues_db.inc");
include_once($path_to_root . "/assets/includes/db/assets_db.inc");


$js = '';
if ($SysPrefs->use_popup_windows) {
	$js .= get_js_open_window(900, 500);
}

if (user_use_date_picker()) {
	$js .= get_js_date_picker();
}
page(_($help_context = "Tool Return"));

//------------------------------------------------------------------------------------------------------
simple_page_mode(true);

$ai_no = -1;
 
if (isset($_GET['AINo']))
{
    $_POST['AINo'] = $_GET['AINo'];
    set_session_variable("ST_TOOL_RETURN_ai_no", $_POST['AINo']);
}

if (isset($_GET['NewOrder']))
{
    $_POST['AINo'] = -1;
    set_session_variable("ST_TOOL_RETURN_ai_no", $_POST['AINo']);
}        
        
if (isset($_POST['AINo']) && $_POST['AINo'] > 0){
    $ai_no = $_POST['AINo'];
}
else{
    $ai_no = get_session_variable("ST_TOOL_RETURN_ai_no");    
}

if (isset($_GET['Added_AI_Id'])) 
{
    //return;
        
    $trans_no = $_GET['Added_AI_Id'];
    $trans_type = ST_TOOL_RETURN;
    $message = "Tool return $trans_no has been created.";
    
	display_notification_centered($message);
        
	display_note(print_document_link($trans_no, _("&Print this tool return"), true, $trans_type), 0, 0);

	hyperlink_no_params("$path_to_root/assets/inquiry/tool_issues_inquiry.php", _("Create another &tool return"));

//	hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=$trans_type&trans_no=$trans_no");

	display_footer_exit();
}


function can_process_ar($ai_no)
{
    $cph_msg = can_process_ar_header($ai_no);
    if($cph_msg["success"] !== true){
        return $cph_msg;
    }
            
    $result_details = get_tool_issue_details($ai_no);     
   
    $s_lines =0;
    while($row_d = db_fetch($result_details)){
        
        if((isset($_POST["selected_".$row_d["id"]])) && ($_POST["selected_".$row_d["id"]] == true))
                 
        {
            $cpl_msg = can_process_ar_line($ai_no, $row_d['id'], $row_d['asset_id'], sql2date($row_d['from_date']));
            if($cpl_msg["success"] !== true){
                return $cpl_msg;
            }
            
            $s_lines++;
        }       
       
    }
    if($s_lines == 0){
        $message = "No Lines Selected";
       return array("success" => false, "focus_to" => '', "message" => $message);
    }
    
   return array("success" => true, "message" => '');
}


function can_process_ar_header($ai_no)
{ 
    global $Refs;
    
    $ar_header = get_tool_issue_header($ai_no);
    $header_id = $ar_header['id'];
      
     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_TOOL_RETURN, $header_id);
    if($ref_msg){
        $message = $ref_msg;
        $set_focus = '';  
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);       
    }
    
    if (!($_POST['project_id'] > 0))
    {
        $message = "Please select a Project.";
        $set_focus = 'project_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    if($_POST['location'] == '')
    {
        $message = "Please select a Location.";
        $set_focus = 'location';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }       
    
    if(!(strlen($_POST['employee_code']) > 1))
    {
        $message = "Please select an employee.";
        $set_focus = 'employee_code';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }      

    if(!is_date($_POST['date']))
    {
        $message = "Date entered is not a valid date.";
        $set_focus = 'date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }
    
    return array("success" => true, "message" => "");     
}

        
function can_process_ar_line($ai_no, $line_id, $asset_id, $from_date)
{
    if(!is_date($_POST['return_date_'.$line_id]))
    {
        $message = "Entered date is not a valid date.";
        $set_focus = 'return_date_'.$line_id;
        return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
    }
       
    
    $issuing_asset = get_asset($asset_id);
    $multiple_items = $issuing_asset['multiple_items'];
    
    if($multiple_items == 1){
        if(!check_num('quantity_'.$line_id, 0.0000001))
        {
            $message = "Quantity should be greater than zero.";
            $set_focus = 'quantity_'.$line_id;
            return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
        }
    }
    
    $asset_issue_detail = get_asset_issue_detail_record($line_id);
    $issued_qty = $asset_issue_detail['quantity'];
    $returned_qty = $asset_issue_detail['returned_qty'];
    
    $asset_details = get_asset($asset_id);
    $multiple_items = $asset_details['multiple_items'];
    
    if($multiple_items == 1){
        $returning_qty = $_POST['quantity_'.$line_id];
    }else{
        $returning_qty = 1;
    }
    
    $total_qty_to_be_returned = $returned_qty + $returning_qty;
    
    if($total_qty_to_be_returned > $issued_qty){
        
        $ai_detail = get_asset_issue_detail_record($line_id);
      
        $asset_details = get_asset($asset_issue_detail['asset_id']);
        
        $error_prefix = "Asset"." "."(".$ai_detail['asset_id'].")"." - ".$asset_details['asset_code']." - ".$asset_details['description']." "."(".'Line id'." - ".$ai_detail['id'].")";
            
        $msg = " Total of returning quantity ($returning_qty) and already returned quantity ($returned_qty) cannot be greater than issued quantity ($issued_qty).";
            
        $message = $error_prefix.$msg;
        $set_focus = '';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
      
    }
    
    if(date1_greater_date2($from_date, $_POST['return_date_'.$line_id]))
    {
        $message = "Returning date cannot be earlier than the issued date.";
        $set_focus = '';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }
    
    return array("success" => true, "message" => "");      
}


function save_ar_header(&$ai_no)
{
  
    $ar_id = add_tool_return_header($ai_no, $_POST['reference'], $_POST['project_id'], 
                                        $_POST['group_company_code'], $_POST['employee_code'],
                                        $_POST['location'], $_POST['date'], $_POST['comment']);
                                              
    if($ar_id > 0){
        set_session_variable("ST_TOOL_RETURN_ai_no", $ar_id);
        return array("success" => true, 'trans_no' => $ar_id,'project_id' => $_POST['project_id'], "message" => "Tool return $ar_id has been saved.");
    }
    else{
        return array("success" => false, 'trans_no' => '','project_id' => $_POST['project_id'], "message" => "Could not save tool return header.");
    }
}


function save_ar_detail(&$ai_no, $asset_return_id, $project_id)
{    
    $ard_details = get_tool_issue_details($ai_no);       
   
        while ($a_row = db_fetch($ard_details))
        {
            if((isset($_POST['selected_'.$a_row['id']])) && ($_POST['selected_'.$a_row['id']] == true))                   
            {        
                $issue_line_id =  $a_row['id'];
                $asset_id = $a_row['asset_id'];              
                $site_id = $_POST['site_id_'.$issue_line_id]; 
                
                
                $a_details = get_asset($asset_id);
                $multiple_items = $a_details['multiple_items'];
                
                if($multiple_items == 1){
                    $qty = $_POST['quantity_'.$issue_line_id];
                }else{
                    $qty = 1;
                }
              
                $date = $_POST['return_date_'.$issue_line_id]; 
                
                $lost = $_POST['lost_'.$issue_line_id]; 
                $comment = $_POST['comment_'.$issue_line_id]; 
                          
                $asset_return_line_id = add_tool_return_line($issue_line_id, $asset_return_id, $asset_id, 
                                        $site_id, $qty, $date, 
                                        $lost, $comment);  

                $return_qty = get_tool_issue_detail_total_returned_qty($issue_line_id);                 
                
                $no_of_rec = update_tool_issue_detail_total_returned_qty($issue_line_id, $return_qty);
                
                if($no_of_rec != 1){
                    return array("success" => false, 'trans_no' => $asset_return_id, "message" => "Another user has updated Asset Issue line $issue_line_id.");
                }  
                
                add_asset_move(ST_TOOL_RETURN, $asset_return_id, $asset_return_line_id, $_POST['reference'], 
                        $date, $asset_return_line_id, $_POST['location'], $site_id, 
                        $a_row['task_id'], $qty, $project_id);                
                
            }
        }
        
        return array("success" => true, 'trans_no' => $asset_return_id, "message" => "");
}

function save_ar(&$ai_no)
{
//    $arh_msg = can_process_ar_header($ai_no);
//    if($arh_msg["success"] !== true) 
//    {          
//        if(isset($arh_msg["focus_to"])){
//            set_focus($arh_msg["focus_to"]);
//        }
//        return array("success" => false, "message" => $arh_msg["message"]);
//    }

    
    $msg = save_ar_header($ai_no);
    if($msg["success"] !== true){
        return $msg;
    }

    $msg = save_ar_detail($ai_no, $msg['trans_no'], $msg['project_id']);
    if($msg["success"] !== true){
        return $msg;
    }
    
    
    
    if(check_tool_issue_fully_returned($ai_no)){
        update_tool_issue_fully_returned($ai_no, $_POST['date']);
    }
              
//    $aih = get_asset_issue_header_record($ai_no);
//    $tool_request_id = $aih['ar_id'];
//    if(check_tool_request_fully_returned($tool_request_id)){
//        $n2 = update_tool_request_fully_returned($tool_request_id);
//        if($n2 != 1){
//            return array("success" => false, 'trans_no' => $ai_id, "message" => "Another user has updated asset request $ar_no.");
//        }
//    }
    return array("success" => true, 'trans_no' => $ai_no, "message" => $msg["message"]);
}

function display_ar_header($ai_no)
{
    global $Refs;
     
    if($ai_no>0){
        
        $ar_header = get_tool_issue_header($ai_no);
        $_POST['project_id'] = $ar_header['project_id'];
              
//        if(!isset($_POST['employee_code'])){
//            $_POST['employee_code'] = $ar_header['employee_code'];
//        }
        if(!isset($_POST['reference'])){
            $_POST['reference'] = $ar_header['reference'];
        }
        
        if(!isset($_POST['group_company_code'])){
            $_POST['group_company_code'] = $ar_header['company_code'];
        }
        
        if(!isset($_POST['employee_code'])){
            $_POST['employee_code'] = $ar_header['employee_code'];
        }
        
        if(!isset($_POST['location'])){
            $_POST['location'] = $ar_header['location'];
        }

        if(!isset($_POST['date'])){
            $_POST['date'] = sql2date($ar_header['tran_date']);
        }

        if(!isset($_POST['project_description'])){
            $_POST['project_description'] = $ar_header['project_description'];
        }
        
        if(!isset($_POST['comment'])){
            $_POST['comment'] = $ar_header['comments'];
        }
    }

        
    start_outer_table(TABLESTYLE2, "width=35%"); // outer table
    start_table(TABLESTYLE2);  
        table_section(1, "50%");
            text_row("Reference:", 'reference', $Refs->get_next(ST_TOOL_RETURN), null, null);   
        
            if($ai_no>0){
                label_row("Project:", $_POST['project_description']);   
                hidden('project_id', $_POST['project_id']);
            }
            else{
               project_list_row(_("Project:"), 'project_id', null, _('Select a project'), true); 
            }
            
            group_companies_list_row("Company:", 'group_company_code', null, false, true);    
            group_company_employees_simple_list_row(_("Employee:"), 'employee_code', $_POST['group_company_code'],'', null, "Select an employee", false);    
            
            asset_locations_list_row("Location:", 'location', null, 'Select Location', false);           
      
            date_row("Date:", "date");

            textarea_row("Comment:", 'comment', null, 35, 2);     

//    end_table(1);
    end_outer_table(2); // outer table
}


function display_ar_details($ai_no)
{  
    global $project_invoice_line_types;    
       
    $result = get_tool_issue_details($ai_no);      
                              
    start_table(TABLESTYLE, "width=90%");
    $th = array(_("ID"), _('Tool'), 
                    _("Issued<br>qty"),_("Returned<br>Qty"),_("This Return<br>Qty"),
                    _("Job"),_("Issued<br>Date"),_("Returned<br>Date"), "Lost", _("Comment"), "");  
    
    table_header($th);
    $k = 0; //row colour counter
       
    while ($myrow = db_fetch($result))
    {
        alt_table_row_color($k);

        label_cell($myrow["id"], "align=right");

        $asset_name = $myrow["asset_code"]." - ".$myrow["asset_description"]." - (".$myrow["asset_id"].")";
        label_cell($asset_name); 
              
//        label_cell($myrow["rate_description"], "align=left");
//        label_cell($myrow["no_of_days"] * $myrow["quantity"], "align=right");
//        label_cell("Used chg units", "align=right");
//        qty_cells(null, 'no_of_days_'.$myrow['id'], null, null, null, 0);
        
        label_cell($myrow['quantity'], "align=center");
        
        label_cell($myrow['returned_qty'], "align=center");
               
        $asset_details = get_asset($myrow['asset_id']);
        $multiple_items = $asset_details['multiple_items'];
        
        if($multiple_items == 0){
            label_cell(1, "align=center");
        }else{
            $_POST['quantity_'.$myrow['id']] = $myrow['quantity'] - $myrow['returned_qty'];
            
            qty_cells(null, 'quantity_'.$myrow['id'], null, null, null, 0);
        }
                    
            
//        project_sites_list_cells(null, 'site_id_'.$myrow["id"], $_POST['project_id'], null, "");
        $_POST['site_id_'.$myrow['id']] = $myrow["site_id"];
        hidden('site_id_'.$myrow['id'], $_POST['site_id_'.$myrow['id']]);
        label_cell($myrow['site_description']);
        
        label_cell(sql2date($myrow['from_date']));
             
        date_cells(null, 'return_date_'.$myrow["id"]);    

        yesno_list_cells(null, 'lost_'.$myrow["id"], null, "Yes", "No");
        
        text_cells(null, 'comment_'.$myrow["id"]);
                                        
//        if($myrow['return_line_id'] > 0){
//            label_cell(null);
//        }else{         
//        }
        
        check_cells(null, 'selected_'.$myrow['id'], null, false);
         
        $k++;                                      
   
        end_row();        
      
    } 
    
    end_table(2);
}


if(isset($_POST['Add_Asset_Return'])){      
       
    $cppd_msg = can_process_ar($ai_no);
    if($cppd_msg['success'] === true){
        begin_transaction();
        $save_ar_msg = save_ar($ai_no);
        if($save_ar_msg['success'] !== true){
            cancel_transaction();
        }else{
            commit_transaction();
            $Mode = 'RESET';
            clear_session_variable("ST_TOOL_RETURN_ai_no");
            meta_forward($_SERVER['PHP_SELF'], "Added_AI_Id=$ai_no");   
        }
    }
    else{
        display_error($cppd_msg['message']);
    }

}

if (isset($_POST['cancel'])){
    $Mode = 'RESET';
    $selected_id = -1;
    unset ($_POST);
}  

//--------------------------------------------------------------------------------------------------------

//if ($Mode == 'Delete')
//{
//        $recs = delete_project_dispatch_request_item($selected_id);
//               
//        if($recs == 1){
//                display_notification(_("Project dispatch request item has been deleted."));
//        }
//        else{
//                display_error(_("Project dispatch request item could not be deleted."));
//        }
//	$Mode = 'RESET';
//}

if ($Mode == 'RESET')
{
	$selected_id = -1;
}
    $Ajax->activate('_page_body');
    $Ajax->activate('pd_items');
//--------------------------------------------------------------------------------------------------------------

start_form();

display_ar_header($ai_no);   

//------------------------------------------------------------------------------------------------------------
         
div_start('pd_items');
display_ar_details($ai_no);
 
div_end();

 
submit_center_first('Add_Asset_Return', _("Process"), '', 'default');
submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');

if (!@$_GET['popup'])
{
    end_form(2);
    end_page(@$_GET['popup'], false, false);        
}


?>
