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

$page_security = 'SA_PROJECT_INVOICE';
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 . "/projects/includes/db/manual_project_invoice_db.inc");
include_once($path_to_root . "/sales/includes/db/sales_invoice_db.inc");
include_once($path_to_root . "/sales/includes/db/cust_trans_db.inc");
include_once($path_to_root . "/includes/approval_functions.inc");
include_once($path_to_root . "/projects/includes/db/project_payment_application_db.inc"); 
include_once($path_to_root . "/reporting/includes/reporting.inc");
include_once($path_to_root . "/sales/includes/db/customers_db.inc"); 
include_once($path_to_root . "/projects/includes/db/projects_db.inc");
include_once($path_to_root . "/projects/includes/ui/manual_project_invoice_ui.inc");
include_once($path_to_root . "/includes/banking_custom.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 = "Manual Project Invoice"), false, false, "", $js);

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

//$pi_no = get_session_variable('project_invoice_no'); 
//if(!($pi_no > 0)){
//    set_session_variable('project_invoice_no', -1);
////    $pi_no = -1;
//}

$pi_no = -1;
 
if (isset($_GET['PINo']))
{
    $_POST['PINo'] = $_GET['PINo'];
}

if (isset($_POST['PINo'])){
    $pi_no = $_POST['PINo'];
}
   //$pi_no = get_session_variable("project_invoice_no");

if (isset($_GET['Released_ID']) || isset($_GET['Sent_Back_ID']) || isset($_GET['Rejected_ID'])) 
{
    if (isset($_GET['Released_ID'])) {
        $trans_no = $_GET['Released_ID'];
    } elseif (isset($_GET['Sent_Back_ID'])) {
        $trans_no = $_GET['Sent_Back_ID'];
    } elseif (isset($_GET['Rejected_ID'])) {
        $trans_no = $_GET['Rejected_ID'];
    }
        
	$trans_type = ST_PROJECT_INVOICE;
    $message = get_session_variable('project_invoice_messages');
    clear_session_variable('project_invoice_messages');
    
	display_notification_centered($message);
        
	display_note(print_document_link($trans_no, _("&Print this Project Invoice"), true, $trans_type), 0, 0);

	hyperlink_no_params("$path_to_root/projects/manual_project_invoice.php", _("Create another &Project Invoice"));

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

	display_footer_exit();
}

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


function _get_completed_date()
{    
    switch ($_POST['line_type']){
            case PILT_MAIN_HEADER:
            case PILT_MAIN_SUMMARY:
            case PILT_SUB_HEADER:
            case PILT_SUB_SUMMARY:
            case PILT_FINAL_TOTAL:
                $_POST['completed_date'] = '';
                break;
    }  
    
    if(is_date($_POST['completed_date'])){
        return $_POST['completed_date'];      
    }
    else{  
        return sql2date(INFINITE_START_DATE);    
    }
}

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


function display_manual_project_invoice_header($pi_no)
{
	global $Refs, $Ajax;
	
        $Ajax->activate('customer_id');
        
    if(list_updated('project_id')){
        $_POST['customer_id'] = '';
        $_POST['_customer_id_edit'] = '';
//        unset($_POST['customer_id']);
    }
    
    if($pi_no>0){
        $mpi_header = get_manual_project_invoice_header($pi_no);
        $project_id = $mpi_header['project_id'];
        $user_id = $_SESSION['wa_current_user']->user;
        $cap = can_access_project($project_id, $user_id);
        if($cap['success'] !== true) 
        {
            display_error($cap["message"]);
            set_focus('project_id');
            display_footer_exit();
            exit;
        } 
        
        if(!in_array($mpi_header['approval_status'], array(AS_NEW, AS_WITH_THE_APPROVER, AS_AWAITING_APPROVAL, AS_BACK_TO_ORIGINATOR))){
            if(!$_SESSION["wa_current_user"]->can_access('SA_EDIT_APPROVED_PROJECT_INVOICES')){
                display_error("This is an approved transaction. You do not have permission to edit it.");
                set_focus('project_id');
                display_footer_exit();
                exit;
            }
        }
        
        
        
        if(!isset($_POST['project_id'])){
            $_POST['project_id'] = $mpi_header['project_id'];
        }
        
        
    
        
        
        
        
        if(!(isset($_POST['customer_id']) && $_POST['customer_id'] > 0)){
            $_POST['customer_id'] = $mpi_header['debtor_no'];
        }
        
        if(!isset($_POST['customer_branch'])){
            $_POST['customer_branch'] = $mpi_header['branch_code'];
        }
        if(!isset($_POST['reference'])){
            $_POST['reference'] = $mpi_header['reference'];
        }
        if(!isset($_POST['payment_terms'])){
            $_POST['payment_terms'] = $mpi_header['payment_terms'];
        }
        if(!isset($_POST['ord_date'])){
            $_POST['ord_date'] = sql2date($mpi_header['ord_date']);
        }
        if(!isset($_POST['salesman_code'])){
            $_POST['salesman_code'] = $mpi_header['salesman_code'];
        }
        if(!isset($_POST['total'])){
            $_POST['total'] = $mpi_header['total'];
        }
        if(!isset($_POST['taxes'])){
            $_POST['taxes'] = $mpi_header['taxes'];
        }
        if(!isset($_POST['payment_application_id'])){
            $_POST['payment_application_id'] = $mpi_header['payment_application_id'];
        }
        if(!isset($_POST['payment_certificate_ref'])){
            $_POST['payment_certificate_ref'] = $mpi_header['payment_certificate_ref'];
        }
        if(!isset($_POST['payment_certificate_amount'])){
            $_POST['payment_certificate_amount'] = $mpi_header['payment_certificate_amount'];
        }
        if(!isset($_POST['tax_group_id'])){
            $_POST['tax_group_id'] = $mpi_header['tax_group_id'];
        }
        if(!isset($_POST['project_sales_order_id'])){
            $_POST['project_sales_order_id'] = $mpi_header['project_sales_order_id'];
        }
        
        $_POST['approval_status'] = $mpi_header['approval_status'];
    }
    else{
        if(!(isset($_POST['reference']) && strlen($_POST['reference']) > 0)){
            $_POST['reference'] = $Refs->get_next(ST_PROJECT_INVOICE);
        }
        $_POST['approval_status'] = 0;
    }
        
    
    
    
    start_outer_table(TABLESTYLE2, "width=90%"); // outer table
    start_table(TABLESTYLE2);  
        table_section(1, "35%");
            project_list_row(_("Project:"), 'project_id', null, _('Select a project'), true);              

            $project_id = $customer_id = 0;
            $rate_include_taxes = null;
            $project = get_project($_POST['project_id']);
            if (isset($project['project_id']) && $project['project_id'] > 0){
                if(!(isset($_POST['customer_id']) && $_POST['customer_id'] > 0)) {
                    $_POST['customer_id'] = $project['customer_id']; 
                }
                
                $project_id = $project['project_id'];
                $customer_id = $project['customer_id'];
                $rate_include_taxes = $project['rate_include_taxes'];
            }

            if(list_updated('project_id')){
                $proj = get_project($_POST['project_id']);
                if($pi_no > 0){
                    if($_POST['project_id'] != $mpi_header['project_id']){                
                        $_POST['customer_id'] = $proj['customer_id'];
                    }
                }
                else{
                    $_POST['customer_id'] = $proj['customer_id'];
                }
            }
            
            
            if($pi_no > 0){
//                $_POST['customer_name'] = get_customer_name($_POST['customer_id']);
//                label_row("Customer:", $_POST['customer_name']);    
//                hidden('customer_id', $_POST['customer_id']);
                customer_list_row("Customer:", 'customer_id', $_POST['customer_id'], 'Please select a customer', true);
            }
            else{
                customer_list_row("Customer:", 'customer_id', null, 'Please select a customer', true);
            } 
            
            customer_branches_list_row("Branch:", $_POST['customer_id'], 'branch_code', null, false, false, false); 
            
            text_row("Reference:", 'reference', null, null, null);      
            
            project_sales_orders_list_row("Customer PO:", 'project_sales_order_id', $project_id, null, '', true);

//        table_section(2, "35%");
            
            date_row("Order Date:", 'ord_date');
            start_row();
            sale_payment_list_cells("Payment Terms:", 'payment_terms', null, null);  
            end_row();     
            sales_persons_list_row("Sales Person:", 'salesman_code', null);
        
        table_section(2, "35%");
            
            project_payment_applications_list_row("Payment Application", 'payment_application_id', $project_id, null, '', true);
            
            $pah_total = 0;
            $pah = get_project_payment_application_header(get_post('payment_application_id'));
            if (isset($pah['order_no']) && $pah['order_no'] > 0) {
                if($pah['rate_include_taxes']){
                    $pah_total = $pah['total'];
                }
                else{
                    $pah_total = $pah['total'] + $pah['taxes'];
                }
            }
            label_row("Payment Application Amount", number_format($pah_total,2));
            text_row("Payment Certificate Reference:", 'payment_certificate_ref', null, null, null); 
            amount_row("Payment Certificate Amount:", 'payment_certificate_amount');   
            
            global $approval_statuses;
            $s = get_project_trans_view_str(ST_APPROVAL_LOG, $pi_no."&source_type_id=".ST_PROJECT_INVOICE, "Approval Status");
            label_row($s,$approval_statuses[$_POST['approval_status']]);

        table_section(2, "30%");
            table_section_title("Revenue Recognition Values");
            amount_row("Total Amount (without taxes):", 'total');   

//            label_row("Price Include Taxes:", get_yes_no_name($project['rate_include_taxes']));
            hidden('rate_include_taxes', $rate_include_taxes);
            
            if(!(isset($_POST['tax_group_id']) && $_POST['tax_group_id'] > 0)){
                $cust_branch = get_cust_branch($_POST['customer_id'], $_POST['branch_code']);
                if (isset($cust_branch['branch_code']) && $cust_branch['branch_code'] > 0) {
                    $_POST['tax_group_id'] = $cust_branch['tax_group_id'];
                }
            }
            
            tax_groups_list_row("Tax Group:", 'tax_group_id', null, "Select a Tax Group", true);
            
            $total_wo_taxes = input_num('total');
            $selected_taxes = display_selected_tax_types($pi_no, get_post('tax_group_id'));  
            
            $taxes_total = $selected_taxes["taxes"];
            $staxes_total = $selected_taxes["staxes"];
            
            $total_with_taxes = $total_wo_taxes + $taxes_total;
            label_row('<b>Total (with taxes):</b>', text_bold(number_format($total_with_taxes,2))); 
        
//    end_table(1);

    end_outer_table(1); // outer table
    hidden('PINo', $pi_no);
    
    if($_POST['customer_id'] != $customer_id && $customer_id > 0){
        $m = "Selected customer is different to the customer of the project. This is NOT allowed for on going transactions.";
        display_note("<font color='red'>$m</font>");
        br(1);
    }

    if($pi_no>0){
        $approval_status = $mpi_header['approval_status'];
        if(!in_array($approval_status, array(AS_NEW, AS_AWAITING_APPROVAL, AS_WITH_THE_APPROVER, AS_BACK_TO_ORIGINATOR))){
            br(2);
            $m = "This is details editing mode only. Header details will not be updated.";
            display_note("<font color='red'>".text_bold($m)."</font>");
            br(2);
        }
    }


}

function display_selected_tax_types($pi_no, $tax_group_id)
{
    $taxes_total = $staxes_total = 0;
    
    $tax_types_array = get_tax_group_items_as_array($tax_group_id);
    foreach ($tax_types_array as $tax_type) {
        if($tax_type['rate'] > 0){
            $tax_amount = get_manual_project_invoice_tax_type_amount($pi_no, $tax_type['tax_type_id']);
            $_POST[$tax_type['tax_type_id'].'_mpi_tax'] = $tax_amount;
            amount_row($tax_type['tax_type_name'], $tax_type['tax_type_id'].'_mpi_tax');   
            
            if($tax_type['suspended'] == 0){
                $taxes_total += $tax_amount;
            }
            else{
                $staxes_total += $tax_amount;
            }
        }
    }
    
    return array("taxes"=>$taxes_total, "staxes"=>$staxes_total);
}

function display_manual_project_invoice_details($pi_no, $selected_id, &$Mode)
{  
    global $project_invoice_line_types;    
          
    $result = get_manual_project_invoice_details($pi_no);  
    
                              
    start_table(TABLESTYLE, "width=95%");
    $th = array(_('Seq.'),_('Details'), _('Date'),
                _('Unit'), _('Quantity'),_('Rate'), _('Amount'), _('Category'), "", "");              

    table_header($th);
    $k = 0; //row colour counter
   // $total = 0;
    
    while ($myrow = db_fetch($result))
    {
        if($selected_id != $myrow["id"]){
            alt_table_row_color($k);


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

    //***********************************
    //           Details
    //***********************************        
            switch ($myrow['line_type']) {
                case PILT_MAIN_HEADER:
                case PILT_MAIN_SUMMARY:
                    label_cell("<b>".$myrow["description"]."</b>");
                    break;
                case PILT_MAIN_ITEM:
                    label_cell(spaces(10).$myrow["description"]);
                    break;
                case PILT_SUB_HEADER:
                case PILT_SUB_SUMMARY:
                    label_cell(spaces(10)."<b>".$myrow["description"]."</b>");
                    break;
                case PILT_SUB_ITEM:
                    label_cell(spaces(20).$myrow["description"]);
                    break;
                case PILT_DETAIL:
                default:
                    label_cell(spaces(30).$myrow["description"]);
                    break;
                case PILT_FINAL_TOTAL:
                    label_cell("<b>".$myrow["description"]."</b>");
                    break;
            }

    //***********************************
    //           Unit, 
    //           Quantity, 
    //           Rate, 
    //           Amount
    //***********************************

            switch ($myrow['line_type']) {
                case PILT_MAIN_HEADER:
                    label_cell("");
                    label_cell("");
                    label_cell("");
                    label_cell("");
                    label_cell("");
                    break;
                case PILT_MAIN_SUMMARY:
                    label_cell("");
                    label_cell("");
                    label_cell("");
                    label_cell("");
                    amount_cell($myrow["amount"], true);
                    break;
                case PILT_MAIN_ITEM:
                    if(is_date(sql2date($myrow["completed_date"]))){
                        label_cell(sql2date($myrow["completed_date"]), "align=center");
                    }
                    else{
                        label_cell('');
                    }
                    label_cell($myrow["unit_name"]);
                    if($myrow["unit_name"] != null && strlen($myrow["unit_name"]) > 0){
                        label_cell(number_format($myrow["quantity"],3), "align=right");
                        label_cell(number_format($myrow["rate"],2), "align=right");
                    }
                    else{
                        label_cell('');
                        label_cell('');
                    }
                    label_cell(number_format($myrow["amount"],2). spaces(10), "align=right");
                    break;
                case PILT_SUB_HEADER:
                    label_cell("");
                    label_cell("");
                    label_cell("");
                    label_cell("");
                    label_cell("");
                    break;
                case PILT_SUB_SUMMARY:
                    label_cell("");
                    label_cell("");
                    label_cell("");
                    label_cell("");
                    label_cell("<b>".$myrow["amount"]."</b>". spaces(10), "align=right");
                    break;
                case PILT_SUB_ITEM:
                    if(is_date(sql2date($myrow["completed_date"]))){
                        label_cell(sql2date($myrow["completed_date"]), "align=center");
                    }
                    else{
                        label_cell('');
                    }
                    label_cell($myrow["unit_name"]);
                    if($myrow["unit_name"] != null && strlen($myrow["unit_name"]) > 0){
                        label_cell(number_format($myrow["quantity"],3), "align=right");
                        label_cell(number_format($myrow["rate"],2), "align=right");
                    }
                    else{
                        label_cell('');
                        label_cell('');
                    }
                    label_cell(number_format($myrow["amount"],2). spaces(10), "align=right");
                    break;
                case PILT_DETAIL:
                default:
                    if(is_date(sql2date($myrow["completed_date"]))){
                        label_cell(sql2date($myrow["completed_date"]), "align=center");
                    }
                    else{
                        label_cell('');
                    }
                    label_cell($myrow["unit_name"]);
                    if($myrow["unit_name"] != null && strlen($myrow["unit_name"]) > 0){
                        label_cell(number_format($myrow["quantity"],3), "align=right");
                        label_cell(number_format($myrow["rate"],2), "align=right");
                    }
                    else{
                        label_cell('');
                        label_cell('');
                    }
                    label_cell(number_format($myrow["amount"],2). spaces(10), "align=right");
                    break;
                case PILT_FINAL_TOTAL:
                    label_cell("");
                    label_cell("");
                    label_cell("");
                    label_cell("");
                    amount_cell($myrow["amount"], true);
                    break;
            }  

            label_cell($myrow["category_name"]);
    //        label_cell($myrow["debit_account"]." - ".$myrow["debit_account_name"]);
    //        label_cell($myrow["credit_account"]." - ".$myrow["credit_account_name"]);        

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

    //        label_cell("[".$project_invoice_line_types[$myrow['line_type']]."]"); 

            end_row();  

            if($myrow["line_comment"] != null && strlen($myrow["line_comment"]) > 0){
                alt_table_row_color($k);
                label_cell($myrow["line_comment"], 'colspan=8');
                label_cell('');
                label_cell('');
                end_row();
            }
        }
        else{
            display_project_invoice_edit_controls($selected_id, $Mode);
        }
    }
    
    if(!($selected_id > 0)){
        display_project_invoice_edit_controls($selected_id, $Mode);
    }
      
}

function display_project_invoice_edit_controls($selected_id, &$Mode)
{
    echo "<td colspan=8>";
    
    if ($Mode =='Edit')   
    {
        $myrow = get_manual_project_invoice_line($selected_id); 

        $_POST['line_type'] = $myrow['line_type'];
        $_POST['unit'] = $myrow["unit"];    
        $_POST['sequence'] = $myrow["sequence"];
        $_POST['description'] = $myrow["description"];    
        $_POST['unit'] = $myrow["unit"];  
        $_POST['quantity'] = $myrow["quantity"]; 
        $_POST['rate'] = $myrow["rate"]; 
        $_POST['amount'] = $myrow["amount"]; 
        $_POST['completed_date'] = sql2date($myrow["completed_date"]); 
        $_POST['line_comment'] = $myrow["line_comment"]; 
        $_POST['category_id'] = $myrow["category_id"];
        $_POST['debit_account'] = $myrow["debit_account"];
        $_POST['credit_account'] = $myrow["credit_account"];

    }
    else{
   
    }

    hidden('selected_id', $selected_id );
    br();

    div_start('billing_items');
//    start_table(TABLESTYLE2);
    start_outer_table(TABLESTYLE2);
    table_section(1);
    
    qty_row("Display Sequence:", 'sequence', null, null, null, 0);   
    project_invoice_line_types_list_row("Line Type:", 'line_type',null,null,true);
    
    text_row("Details:", 'description', null, 50, 500);
    
    switch ($_POST['line_type']) {
        case PILT_MAIN_HEADER:
        case PILT_SUB_HEADER:
            hidden('completed_date', '');
            hidden('unit', '');
            hidden('quantity', 0.000);
            hidden('rate', 0.00);
            hidden('amount', 0.000);
            break;
        case PILT_MAIN_SUMMARY:       
        case PILT_SUB_SUMMARY:
        case PILT_FINAL_TOTAL:
            hidden('completed_date', '');
            hidden('unit', '');
            hidden('quantity', 0.000);
            hidden('rate', 0.00);
            amount_row("Amount:", 'amount', null, null, null, 2); 
            break;
        default:      
            date_row("Date", 'completed_date');
            stock_units_list_row(_("Units:"), 'unit', null, true, '', true);

            if($_POST['unit'] == ''){
                hidden('quantity', 0.000);
                hidden('rate', 0.00);
                amount_row("Amount:", 'amount', null, null, null, 2);    
            }
            else{
                amount_row("Quantity:", 'quantity', null, null, null, 3);   
                amount_row("Rate:", 'rate', null, null, null, 2); 

                $amount = input_num('quantity') * input_num('rate');
                hidden('amount', $amount);
            }
            break;
    }
    
    table_section(2);
    value_list_row("Line Category", 'category_id', "PROJ_INV_LINE_CATEGORIES", null, "Select a line category");
    
    
//    gl_all_accounts_list_row(_("Debit Account:"), 'debit_account', null, false, false, "");
//    gl_all_accounts_list_row(_("Credit Account:"), 'credit_account', null, false, false, "");

    hidden('debit_account', '');
    hidden('credit_account', '');
    
    textarea_row("Line Comment:", 'line_comment', null, 35, 4);

       
//    end_table(1);
    end_outer_table(1);
    
    if ($selected_id > 0)	{
            button_cell('Update_MPI_Item', _("Update"), _('Confirm changes'), ICON_UPDATE);
            button_cell('cancel', _("Cancel"), _('Cancel changes'), ICON_CANCEL);
            hidden('LineNo', $selected_id);
            set_focus('sequence');
    }
    else
    {
            submit_cells('Add_MPI_Item', _("Add Item"), "colspan=2 align=center", _('Add new item to document'), true);
//            submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
    }
    
    div_end();

    echo "</td>";
    
//    if($selected_id > 0){
//        submit_center_first('Update_MPI_Item', _("Update"), '', 'default');
//        submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
//    }
//    else{        
//        submit_center_first('Add_MPI_Item', _("ADD"), '', 'default');
//        submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
//    }
}


function send_pi_back_to_originator($pi_no, $MPI)
{    
   $msg = can_process_pi_header($pi_no, $MPI);
    if($msg['success'] !== true){
        return $msg;
    }
    
    begin_transaction();
    $pih = get_manual_project_invoice_header($pi_no);

    if($pih['rate_include_taxes']){
        $pi_total = $pih['total'];
    }
    else{
        $pi_total = $pih['total'] + $pih['taxes'];
    }
    
    $current_user_id = $_SESSION['wa_current_user']->user;

    $sbdo_msg = send_back_to_document_originator(ST_PROJECT_INVOICE, $pi_no, $pih['project_id'],
                                    $pih['next_approval_group_id'], $current_user_id, $pih['row_state'], 
                                    $pih['created_by']);
    
    if($sbdo_msg['success'] !== true){
        cancel_transaction();
        return $sbdo_msg;
    }
    else{
        commit_transaction();
        return $sbdo_msg;
    }
}

function reject_pi($pi_no, $MPI)
{
    $msg = can_process_pi_header($pi_no, $MPI);
    if($msg['success'] !== true){
        return $msg;
    }

    begin_transaction();
    $pih = get_manual_project_invoice_header($pi_no);

    if($pih['rate_include_taxes']){
        $pi_total = $pih['total'];
    }
    else{
        $pi_total = $pih['total'] + $pih['taxes'];
    }
    
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $rj_msg = reject_document(ST_PROJECT_INVOICE, $pi_no, $pih['project_id'],
                    $pih['next_approval_group_id'], $current_user_id, $pih['row_state']);
    
    if($rj_msg['success'] !== true){
        cancel_transaction();
        return $rj_msg;
    }
    else{
        commit_transaction();
        return $rj_msg;
    }

}


function create_manual_project_invoice_array(&$MPI)
{
    //header
    $MPI['project_id'] = $_POST['project_id']; 
    $MPI['customer_id'] = $_POST['customer_id']; 
    $MPI['branch_code'] = $_POST['branch_code'];  
    $MPI['reference'] = $_POST['reference']; 
    $MPI['payment_terms'] = $_POST['payment_terms']; 
    $MPI['ord_date'] = $_POST['ord_date']; 
    $MPI['salesman_code'] = $_POST['salesman_code'];  
    $MPI['total'] = input_num('total');  
    $MPI['rate_include_taxes'] = input_num('rate_include_taxes');                                  
    $MPI['payment_application_id'] = $_POST['payment_application_id']; 
    $MPI['payment_certificate_ref'] = $_POST['payment_certificate_ref']; 
    $MPI['payment_certificate_amount'] = input_num('payment_certificate_amount');    
    $MPI['comments'] = '';
    $MPI['tax_group_id'] = $_POST['tax_group_id'];     
    $MPI['project_sales_order_id'] = $_POST['project_sales_order_id'];
    
    //details
    $MPI['line_type'] = $_POST['line_type'];
    $MPI['sequence'] = input_num('sequence'); 
    $MPI['description'] = $_POST['description']; 
    $MPI['completed_date'] = _get_completed_date(); 
    $MPI['unit'] = $_POST['unit']; 
    $MPI['quantity'] = input_num('quantity');
    $MPI['rate'] = input_num('rate');
    $MPI['amount'] = input_num('amount'); 
    $MPI['line_comment'] = $_POST['line_comment'];
    $MPI['category_id'] = $_POST['category_id']; 
    $MPI['debit_account'] = $_POST['debit_account']; 
    $MPI['credit_account'] = $_POST['credit_account'];
    
            
    $tax_group_id = get_post('tax_group_id');
    $tax_types_array = get_tax_group_items_as_array($tax_group_id);
    foreach ($tax_types_array as $tax_type){
        if(isset($_POST[$tax_type['tax_type_id'].'_mpi_tax']) && input_num($tax_type['tax_type_id'].'_mpi_tax') > 0){
            $MPI[$tax_type['tax_type_id'].'_mpi_tax'] = input_num($tax_type['tax_type_id'].'_mpi_tax');
     
        }
    }
}

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


if (isset($_POST['Release_MPI'])){
    
    $MPI = array();
    create_manual_project_invoice_array($MPI);
    
    $crmpi_msg = can_release_mpi($pi_no);
    if($crmpi_msg['success'] !== true){
        display_error($crmpi_msg['message']);
    } else {
    
        $release_msg = release_for_approval_mpi($pi_no, $MPI);
        if($release_msg['success'] !== true){
            display_error($release_msg['message']);
        }
        else{
            new_doc_date($_POST['ord_date']);
            set_session_variable('project_invoice_messages', $release_msg['message']);
            meta_forward($_SERVER['PHP_SELF'], "Released_ID=$pi_no");
        }  
    }
} 

if (isset($_POST['Back_To_Originator_MPI'])){

    $MPI = array();
    create_manual_project_invoice_array($MPI);
    
    $sent_back_msg = send_pi_back_to_originator($pi_no, $MPI);
    if($sent_back_msg['success'] !== true){
        display_error($sent_back_msg['message']);
    }
    else{
        new_doc_date($_POST['ord_date']);
        set_session_variable('project_invoice_messages', $sent_back_msg['message']);
        meta_forward($_SERVER['PHP_SELF'], "Sent_Back_ID=$pi_no");
    }        
} 


if (isset($_POST['Reject_MPI'])){

    $MPI = array();
    create_manual_project_invoice_array($MPI);
    
    $reject_msg = reject_pi($pi_no, $MPI);
        if($reject_msg['success'] !== true){
        display_error($reject_msg['message']);
    }
    else{
        new_doc_date($_POST['ord_date']);
        set_session_variable('project_invoice_messages', $reject_msg['message']);
        meta_forward($_SERVER['PHP_SELF'], "Rejected_ID=$pi_no");
    }
        
} 


if(isset($_POST['Save_MPI_Header'])){
           
    $MPI = array();
    create_manual_project_invoice_array($MPI);
    
    $msg = save_manual_project_invoice_header($pi_no, $MPI);
    
    if($msg['success'] !== true){
        display_error($msg['message']);
    }
    else{
        $_POST['PINo'] = $msg['trans_no'];
        display_notification($msg['message']);
        $Mode = 'RESET';
    }
}


if(isset($_POST['Add_MPI_Item']) || isset($_POST['Update_MPI_Item'])){
        
    $MPI = array();
    create_manual_project_invoice_array($MPI);
     
    $msg = save_manual_project_invoice($pi_no, $selected_id, $MPI);
    
    if($msg['success'] !== true){
        display_error($msg['message']);
    }
    else{
        $_POST['PINo'] = $msg['trans_no'];
        display_notification($msg['message']);
        $Mode = 'RESET';
    }
}


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

if ($Mode == 'Delete')
{
    $manu_proj_inv_h = get_manual_project_invoice_header($pi_no);
    if(is_array($manu_proj_inv_h)){
        $approval_status = $manu_proj_inv_h['approval_status'];
    }
    
    if ($approval_status == AS_REJECTED) {
        display_error("This Manual Project Invoice is already rejected, not allow to further update.");
    } else {
        $recs = delete_manual_project_invoice_item($selected_id);
        
        if($recs == 1){
                display_notification(_("Manual Project invoice item has been deleted."));
        }
        else{
                display_error(_("Manual Project invoice item could not be deleted."));
        }
    }
	$Mode = 'RESET';
}

if ($Mode == 'RESET')
{
	$selected_id = -1;
}
    $Ajax->activate('_page_body');
    $Ajax->activate('billing_items');
//--------------------------------------------------------------------------------------------------------------
if (!@$_GET['popup'])
start_form();

$pi_header = display_manual_project_invoice_header($pi_no);   

$approval_status = 0;
if($pi_no>0){
    $manu_proj_inv_h = get_manual_project_invoice_header($pi_no);
    if(is_array($manu_proj_inv_h)){
        $approval_status = $manu_proj_inv_h['approval_status'];
    }
}

//br();

if(in_array($approval_status, array(AS_NEW, AS_AWAITING_APPROVAL, AS_WITH_THE_APPROVER, AS_BACK_TO_ORIGINATOR))){
    submit_center_first('Save_MPI_Header', _("Save"), '', 'default');

    if($pi_no>0 && !($selected_id > 0)){
        br(2); 
        submit_center_first('Release_MPI', "Release for Approval", '', 'default');
        submit('Back_To_Originator_MPI', 'Back To Originator', true, '', 'default');
        submit_center_last('Reject_MPI', "Reject", '', 'default');	
    }
}

br(2);


//------------------------------------------------------------------------------------------------------------
         
display_manual_project_invoice_details($pi_no, $selected_id, $Mode);

//hidden('PINo',$pi_no);
//inactive_control_row($th);
end_table(1);
//-----------------------------------------------------------------------------------------------------------

//display_project_invoice_edit_controls($selected_id, $Mode);

//if($selected_id > 0){
//    submit_center_first('Update_MPI_Item', _("Update"), '', 'default');
//    submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
//}
//else{        
//    submit_center_first('Add_MPI_Item', _("ADD"), '', 'default');
//    submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
//}

br();


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


?>
