<?php

function display_asset_transfers_header($at_id) {
    global $Refs;
    
    if ($at_id > 0) {
        
        $at_header = get_asset_transfer_header_details($at_id);
            $user_id = $_SESSION['wa_current_user']->user;

            $from_project_id = $_POST['from_project_id'] = $at_header['from_project_id'];
            $cap = can_access_project($from_project_id, $user_id);
            if($cap['success'] !== true){
                display_error($cap["message"]);
                set_focus('from_project_id');
                display_footer_exit();
                exit;
            }

            $to_project_id = $_POST['to_project_id'] = $at_header['to_project_id'];
            $cap = can_access_project($to_project_id, $user_id);
            if($cap['success'] !== true){
                display_error($cap["message"]);
                set_focus('to_project_id');
                display_footer_exit();
                exit;
            }  
     
        if(!isset($_POST['reference'])){
            $_POST['reference'] = $at_header['reference'];
        }
        if(!isset($_POST['comment'])){
            $_POST['comment'] = $at_header['comment'];
        }          
        if(!isset($_POST['from_project_id'])){
            $_POST['from_project_id'] = $at_header['from_project_id'];
        }
        if(!isset($_POST['to_project_id'])){
            $_POST['to_project_id'] = $at_header['to_project_id'];
        }
        if(!isset($_POST['from_location'])){
            $_POST['from_location'] = $at_header['from_asset_location'];
        }
        if(!isset($_POST['to_location'])){
            $_POST['to_location'] = $at_header['to_asset_location'];
        }
        if(!isset($_POST['tran_date'])){
            $_POST['tran_date'] = sql2date($at_header['tran_date']);
        }
        if(!isset($_POST['from_project_description'])){
            $_POST['from_project_description'] = $at_header['from_project_description'];
        }
        if(!isset($_POST['to_project_description'])){
            $_POST['to_project_description'] = $at_header['to_project_description'];
        }
        if (! isset($_POST['approval_status'])) {
            $_POST['approval_status'] = $at_header['approval_status'];
        }
        if (! isset($_POST['company_code'])) {
            $_POST['company_code'] = $at_header['company_code'];
        }
        if (! isset($_POST['employee_code'])) {
            $_POST['employee_code'] = $at_header['employee_code'];
        }
        $_POST['from_location_name'] = $at_header['from_location_name'];
        $_POST['to_location_name'] = $at_header['to_location_name'];
    }else{
        $_POST['reference'] = $Refs->get_next(ST_ASSET_TRANSFER);            
        $_POST['approval_status'] = 0;
    }
  
    start_outer_table(TABLESTYLE2); // outer table
        start_table(TABLESTYLE2);  
            table_section(1, "50%");

                if ($at_id > 0) {
                    label_row("Asset Transfer:", "#".$at_id);
                    $at_hd = get_asset_transfer_header_record($at_id);
                    $reference = $at_hd['reference'];            
                    text_row("Reference:", 'reference', $reference, null, null);            
                } else {            
                    text_row("Reference:", 'reference', $Refs->get_next(ST_ASSET_TRANSFER), null, null);   
                }
                
                project_list_row(_("From Project (Approval):"), 'from_project_id', null, _('Select from project'), true);                         
                project_list_row(_("To Project:"), 'to_project_id', null, _('Select to project'), true); 
                asset_locations_list_row("From Location:", 'from_location', null, 'Select From Asset Location', false);   
                asset_locations_list_row("To Location:", 'to_location', null, 'Select To Asset Location', false); 
                
            table_section(2, "50%");
                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, "", true);
                textarea_row("Comment:", 'comment', null, 30, 3); 
                global $approval_statuses;
                label_row("Approval Status:", $approval_statuses[$_POST['approval_status']]);

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

function display_asset_transfers_details($at_id, $selected_id) {  

    display_heading("Assets Transfer Details"); br();
    
                              
    start_table(TABLESTYLE, "width=98%");
    $th = array(_("ID"), _("Asset"), _('From Site'), _('To Site'), _("Comment"), _("Quantity"), _("Value"), _("Line Total"), "", "");                     

    table_header($th);
    $k = 0; //row colour counter

    $line_total = 0;
            
        $result = get_asset_transfer_details_by_at_id($at_id);      
            while ($row = db_fetch($result)) {

                if (isset($selected_id) && $selected_id == -1 || $selected_id != $row['id']) {
                    alt_table_row_color($k);

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

                        edit_button_cell("Edit".$row["id"], _("Edit"));    
                        delete_button_cell("Delete".$row["id"], _("Delete"));  

                    end_row();
                } else {
                    $line_cost = $row["current_value"] * $row["quantity"];
                    display_asset_transfer_edit_controls($selected_id, "Edit");
                    hidden("selected_id", $selected_id);
                }

                $line_total += $line_cost;
            }
            
        if (isset($selected_id) && $selected_id == -1 || !($selected_id > 0)) {
            display_asset_transfer_edit_controls();
        }
        
        start_row();
            label_cell("Total:", "colspan=7 align=right");
            amount_cell($line_total, true); 
        end_row();  
    
    
    end_table();

    hidden("line_total", $line_total);
}

function display_asset_transfer_edit_controls($selected_id=-1, $Mode=null) {
    global $Ajax;

    if($Mode == "Edit"){
        if($selected_id > 0){      
            $row = get_asset_transfer_detail_line($selected_id); 
            $_POST['id'] = $row["id"];
            
            if(isset($_POST['previous_selected_id']) && $_POST['previous_selected_id'] != $selected_id){
                unset($_POST['asset_id']);
                unset($_POST['_asset_id_edit']);
            }
            if(!(isset($_POST['asset_id']) && $_POST['asset_id'] > 0)){
                unset($_POST['asset_id']);
                unset($_POST['_asset_id_edit']);
                $_POST['asset_id'] = $row["asset_id"];
            }
            $_POST['from_site_id'] = $row["from_site_id"];
            $_POST['to_site_id'] = $row["to_site_id"];
            $_POST['line_comment'] = $row["line_comment"]; 
            $_POST['quantity'] = $row["quantity"]; 
            
            hidden("previous_selected_id", $selected_id);
        }
    }

    echo "<td colspan=8>";
    start_outer_table();

        table_section(1, "10%");
        table_section(2, "30%");

            if($selected_id > 0){  
                label_row("ID:", $row["id"]);
                hidden('asset_id', $_POST['asset_id']);
                $asset_d = get_asset($_POST['asset_id']);
                label_row("Asset:", $asset_d["asset_code"]."-".$asset_d["description"]."-"."(".$asset_d["asset_id"].")");
                hidden('asset_id', $_POST['asset_id']);
            }else{
                $Ajax->activate("asset_list");
                div_start("asset_list");
                    asset_list_row("Asset List:", "asset_id");
                div_end();
            }
            
            $asset_details = get_asset($_POST['asset_id']);
            $multiple_items = $asset_details['multiple_items'];
            $_POST['current_value'] = $asset_details['current_value'];

            if($multiple_items == true){            
                amount_row("Quantity:", 'quantity', null, null);  
            }else{
                if($selected_id > 0 || $_POST['asset_id'] > 0){
                    label_row("Quantity:", number_format(1, 2));
                    hidden('quantity', 1);
                }
            }

        table_section(3, "20%");
        
            if($multiple_items == true){            
                label_row("Value:", number_format($_POST['current_value'], 2));
            }else{
                $qty_one = 1;
                if(isset($_POST['asset_id']) && $_POST['asset_id'] > 0){                        
                    label_row("Value:", number_format($_POST['current_value'], 2));
                }
            }
            project_sites_list_row("From Site:", 'from_site_id', $_POST['from_project_id'], null, '', false);     
            project_sites_list_row("To Site:", 'to_site_id', $_POST['to_project_id'], null, '', false); 

        table_section(4, "30%");
            textarea_row("Comment:", 'line_comment', null, 35, 3); 

        table_section(5, "10%");

    end_outer_table();
    echo "</td>";
    
    if ($selected_id > 0){
        button_cell('Update_Asset_tranfer', _("Update"), _('Confirm changes'), ICON_UPDATE);
        button_cell('cancel', _("Cancel"), _('Cancel changes'), ICON_CANCEL);
    }else{
        submit_cells('Add_Asset_Transfer', _("Add Item"), "colspan=2", _('Add new item to document'), true);
    }
}

function can_process_asset_transfer_header_line($at_id){  
    $msg = can_process_asset_transfer_header($at_id);
        if($msg['success'] !== true){
            if(isset($msg["focus_to"])){
                set_focus($msg["focus_to"]);            
            }
            return $msg;
        }
        
    if(!isset($_POST['Save_Asset_Transfer_Header'])){
        $msg2 = can_process_asset_transfer_line();
        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_header($at_id) {  
    global $Refs;
    $at_header["row_state"] = null; 
    
    $at_header = get_asset_transfer_header_record($at_id);
    $trans_no = $at_header['trans_no'];
      
    if ($at_id > 0) {
        if(!($at_header['approval_status'] == AS_NEW)){
        
            $message = ("This document status does not allow further updating.");
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "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, $trans_no);
        if($ref_msg){
            $message = $ref_msg;
            $set_focus = 'reference';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);       
        }
       
    if(!($_POST['from_project_id'] > 0)){
        $message = "Please select from Project.";
        $set_focus = 'from_project_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    if(!($_POST['to_project_id'] > 0)){
        $message = "Please select to Project.";
        $set_focus = 'to_project_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }

    if($_POST['from_location'] == ''){
        $message = "Please select a From Location.";
        $set_focus = 'from_location';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    if($_POST['to_location'] == ''){
        $message = "Please select a To Location.";
        $set_focus = 'to_location';
        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);        
    }
  
    return array("success" => true, "message" => "", "row_state" => $at_header["row_state"]);    
}

function can_process_asset_transfer_line(){

    if(!($_POST['asset_id'] > 0)){
        $message = "Please select an asset.";
        $set_focus = 'asset_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }

    $asset_details = get_asset($_POST['asset_id']);
    $multiple_items = $asset_details['multiple_items'];
    if($multiple_items == 1){
        if(!(check_num('quantity', 0.00001))){
            $message = "Quantity should be greater than zero.";
            $set_focus = 'quantity';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
        }
    }else{
        if(input_num('quantity') > 1){
            $message = "This is a single item asset. Quantity should be one.";
            $set_focus = 'quantity';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
        }
    }
    
    if($_POST['from_project_id'] == $_POST['to_project_id'] && $_POST['from_location'] == $_POST['to_location']){ 
       if(isset($_POST['from_site_id']) && $_POST['from_site_id'] > 0  && isset($_POST['to_site_id']) && $_POST['to_site_id'] > 0){
           if($_POST['from_site_id'] == $_POST['to_site_id']){
                $message = "Please select different sites with same Project and same Location.";
                $set_focus = 'to_site_id';
                return array("success" => false, "focus_to" => $set_focus, "message" => $message);
           }
       }
    }

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

function save_asset_transfers(&$at_id, $selected_id, $row_state) {
    $msg = save_asset_transfer_header($at_id);
        if($msg["success"] !== true){
            return $msg;
        }
        
    $trans_no = $msg['trans_no'];
    
    $msg = save_asset_transfer_detail($at_id, $selected_id, $trans_no);
        if($msg['success'] !== true){
            return array("success" => false, 'at_id' => $at_id, "message" => $msg['message']);
        }
        
    $msg = update_asset_transfer_header_total($at_id, $row_state);
        if($msg['success'] !== true){
            return array("success" => false, 'at_id' => $at_id, "message" => $msg['message']);
        }

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

function save_asset_transfer_header(&$at_id) {
    $trans_type = ST_ASSET_TRANSFER;
    
        if ($at_id > 0) {
            $ath_row = get_asset_transfer_header_record($at_id);
                $trans_no = $ath_row['trans_no'];
        } else {
            $trans_no = get_next_trans_no($trans_type);
        }
    
    $approval_status = AS_NEW;
    
    
    $msg = write_asset_transfer_header(0, $_POST['reference'], $_POST['company_code'], $_POST['employee_code'], $_POST['tran_date'], 
                                       $_POST['comment'], input_num('line_total'), $trans_type, $trans_no, $approval_status, $_POST['from_project_id'], 
                                       $_POST['to_project_id'], $_POST['from_location'], $_POST['to_location'], $at_id);  
    
    $at_id = $msg['at_id'];
                         
        return $msg;
}

function save_asset_transfer_detail(&$at_id, $selected_id, $trans_no) {    
    $row_state = 0;
    $trans_type = ST_ASSET_TRANSFER;
    $current_value = get_asset($_POST['asset_id']);
    
    if($selected_id > 0){
        $line = get_asset_transfer_detail_line($selected_id);
        $row_state = $line['row_state'];
    }
    
    $msg = write_asset_transfer_line($at_id, $selected_id, $_POST['asset_id'], input_num('quantity'), $current_value['current_value'], 
                                     $_POST['from_site_id'], $_POST['to_site_id'], $_POST['line_comment'], $trans_type, $trans_no, $row_state); 
    
        return $msg;
}

function can_delete_asset_transfer_details_line($at_id) {
   $arh = get_asset_transfer_header_record($at_id);
   
        if (is_array($arh)) {
            if (! ($arh['approval_status'] == AS_NEW)) {
                $message = ("This document status does not allow further updating.");
                $set_focus = '';
                return array("success" => false, "focus_to" => $set_focus, "message" => $message);
            }
        } 
   
    return array("success" => true, "focus_to" => '', "message" => "");       
}

function can_approve_asset_transfer($at_id) {
    $at_hd = get_asset_transfer_header_record($at_id);
    
//    $line_count = get_asset_transfer_detail_lines_total($at_hd['type'], $at_hd['trans_no']);
    $line_count = get_asset_transfer_details_line_count($at_id);
        if (! ($line_count > 0)) {
            $message = ("There are no asset transfer details entered. Can not release this asset transfer.");
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
    
    return array("success" => true, "focus_to" => '', "message" => "", "row_state" => $at_hd['row_state']);    
}

function approve_asset_transfer($at_id, $row_state) {    
    
    $msg = save_asset_transfer_header($at_id, $row_state);
        if($msg['success'] !== true){
            cancel_transaction();
            display_error($msg['message']);
            return $msg;
        } 

    $nof_af_row = update_asset_transfer_approval_status($at_id, AS_NEW, AS_APPROVED);
        if ($nof_af_row != 1) {
            cancel_transaction();
            return array("success" => false, "message" => "Could not approve Asset Transfer Record #$at_id.");
        }
        
        $ath_row = get_asset_transfer_header_record($at_id);
            $trans_no = $ath_row['trans_no'];
            $reference = $ath_row['reference'];
            $tran_date = sql2date($ath_row['tran_date']);
            $from_project_id = $ath_row['from_project_id'];
            $to_project_id = $ath_row['to_project_id'];
            $from_asset_location = $ath_row['from_asset_location'];
            $to_asset_location = $ath_row['to_asset_location'];
            $trans_type = ST_ASSET_TRANSFER;
            
            $result = get_asset_transfer_details_by_at_id($at_id);      
                while ($row = db_fetch($result)) {
        
                    add_asset_move($trans_type, $trans_no, $row['id'], $reference, $tran_date, $row['asset_id'], $from_asset_location, 
                                   $row['from_site_id'], 0, -$row['quantity'], $from_project_id, $row['asset_value']);

                    add_asset_move($trans_type, $trans_no, $row['id'], $reference, $tran_date, $row['asset_id'], $to_asset_location, 
                                   $row['to_site_id'], 0, $row['quantity'], $to_project_id, $row['asset_value']);
                }
        
    commit_transaction();
    
    set_session_variable('ST_ASSET_TRANSFER_message', $msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "Processed_AT_No=$at_id");    
}

?>