<?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 . "/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 . "/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");


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

if (user_use_date_picker()) {
	$js .= get_js_date_picker();
}

global $systypes_array;

page(_($help_context = "Copy ".$systypes_array[ST_PROJECT_INVOICE]), false, false, "", $js);

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

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

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

if (isset($_GET['Copied_ID'])) {
    $trans_no = $_GET['Copied_ID'];
    $message = $_GET['message'];
    
	display_notification_centered($message);
        
	hyperlink_no_params("$path_to_root/projects/manual_project_invoice.php?PINo=$trans_no", _("Edit copied &Project Invoice #$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 '';    
    }
}

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


function display_copy_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'] = '';
    }
    
    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(!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'];
        
        if(!(isset($_POST['reference']) && strlen($_POST['reference']) > 0)){
            $_POST['reference'] = $Refs->get_next(ST_PROJECT_INVOICE);
        }
        $_POST['approval_status'] = 0;
    }
    else{
        
    }
        
    start_outer_table(TABLESTYLE2, "width=85%"); // outer table
    start_table(TABLESTYLE2);  
        table_section(1, "35%");

            $project = get_project($_POST['project_id']);
            if(!(isset($_POST['customer_id']) && $_POST['customer_id'] > 0)){
                $_POST['customer_id'] = $project['customer_id']; 
            }
            
            label_row('Project:', $project['description']);
            label_row('Customer:', get_customer_name($project['customer_id']));
            
            hidden('project_id', $project['project_id']);
            hidden('customer_id', $project['customer_id']);

            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['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['project_id'], null, '', true);
            
            $pah = get_project_payment_application_header(get_post('payment_application_id'));
            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', $project['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']);
                $_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);
    
}

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(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(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(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"]);
//
//            end_row();  
//
//            if(strlen($myrow["line_comment"]) > 0){
//                alt_table_row_color($k);
//                label_cell($myrow["line_comment"], 'colspan=8');
//                end_row();
//            }
//        }
//        else{
//            display_project_invoice_edit_controls($selected_id, $Mode);
//        }
//    }
//    
//}

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'];
    
    $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['COPY_MPI'])) {
    $MPI = array();
    create_manual_project_invoice_array($MPI);
    
    $old_pi_no = $pi_no;
    $pi_no = -1;
    
        begin_transaction();
        $msg = save_manual_project_invoice_header($pi_no, $MPI);
            if ($msg['success'] !== true) {
                cancel_transaction();
                $pi_no = $old_pi_no;
                display_error($msg['message']);

            } else {
                $msg2 = copy_and_save_manual_project_invoice_details($pi_no, $old_pi_no);
                if ($msg2['success'] !== true) {
                    cancel_transaction();
                    $pi_no = $old_pi_no;
                    display_error($msg2['message']);
                } else {
                    commit_transaction();
                    meta_forward($_SERVER['PHP_SELF'], "Copied_ID=$pi_no&message=".$msg2['message']);
                }
            }
          
}

    $Ajax->activate('_page_body');
    $Ajax->activate('billing_items');
    
    
//--------------------------------------------------------------------------------------------------------------
    
    
if (!@$_GET['popup'])
start_form();

br(2);

$pi_header = display_copy_manual_project_invoice_header($pi_no);   

br(2);


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

start_table(TABLESTYLE_NOBORDER);
start_row();
$link = get_project_trans_view_str(ST_PROJECT_INVOICE, $pi_no, "View Copying From ".$systypes_array[ST_PROJECT_INVOICE]);
label_cell($link);
end_row();
end_table(2);

submit_center_first('COPY_MPI', "Copy".$systypes_array[ST_PROJECT_INVOICE], '', 'default');


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


?>
