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


function can_process_pi_header($pi_no, $MPI)
{
    if($pi_no > 0){
        $pih = get_manual_project_invoice_header($pi_no);
        if(!$_SESSION["wa_current_user"]->can_access('SA_EDIT_APPROVED_PROJECT_INVOICES')){            
            if(!($pih['approval_status'] == AS_NEW || $pih['approval_status'] == AS_WITH_THE_APPROVER || $pih['approval_status'] == AS_AWAITING_APPROVAL || $pih['approval_status'] == AS_BACK_TO_ORIGINATOR)){
                $message = ("This Project Invoice status does not allow further updating.");
                return array("success" => false, "focus_to" => '', "message" => $message);
            }
        }
    }
    
    if(!($MPI['customer_id'] > 0)){
        $message = "Please select a customer";
        $set_focus = 'customer_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }     

    if (!($MPI['project_id'] > 0))
    {
        $message = "Please select a Project.";
        $set_focus = 'project_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    if($pi_no > 0){        
        $current_user_id = $_SESSION['wa_current_user']->user;
        $ced_msg = can_edit_document(ST_PROJECT_INVOICE, $MPI['project_id'], $pih['next_approval_group_id'] , $current_user_id, $pih['created_by'], $pi_no);
        if($ced_msg['success'] !== true){
            return array("success" => false, "focus_to" => '', "message" => $ced_msg['message']);
        }
    } 
    
    if(!($MPI['branch_code'] > 0))
    {
        $message = "Please select a customer branch.";
        $set_focus = 'branch_code';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }      

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

    if(!(strlen($MPI['reference']) > 0))
    {
        $message = "Refence can not be empty.";
        $set_focus = 'refence';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }
      
    return array("success" => true, "message" => "");    
}

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

function can_release_mpi($mpi_id)
{
    $set_focus = '';
    
    $line_count = get_manual_project_invoice_line_count($mpi_id);
    if (!($line_count > 0))
    {
        $message = ("There are no project invoice details entered. Can not release this document.");        
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);    
    }
    

    $pih = get_manual_project_invoice_header($mpi_id);
    if(!($pih['approval_status'] == AS_NEW || $pih['approval_status'] == AS_WITH_THE_APPROVER || $pih['approval_status'] == AS_AWAITING_APPROVAL || $pih['approval_status'] == AS_BACK_TO_ORIGINATOR)){
        $message = ("This Project Invoice status does not allow further updating.");
        return array("success" => false, "focus_to" => '', "message" => $message);
    }
    
    if (!is_date_in_fiscalyear($pih['ord_date'], true)) 
    {
        $message = (_("The entered date is not in fiscal year.")); 
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);      
    } 
    
    $msg = is_accounting_period_open($pih['ord_date'], true);
    if ($msg['success'] !== true)
    {
        $message = ($msg['message']); 
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);      
    }
        
    
    
    return array("success" => true, "focus_to" => $set_focus, "message" => '');    
}

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


function can_process_pi_detail($MPI)
{    
    if(!($MPI['line_type'] == PILT_MAIN_HEADER || 
            $MPI['line_type'] == PILT_MAIN_SUMMARY || 
                $MPI['line_type'] == PILT_SUB_HEADER || 
                    $MPI['line_type'] == PILT_SUB_SUMMARY || 
                        $MPI['line_type'] == PILT_FINAL_TOTAL)){
        if(!is_date($MPI['completed_date']))
        {
            $message = "Line date entered is not a valid date.";
            $set_focus = 'completed_date';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
        }
    }
    
    if(!check_num2($MPI['quantity'], 0))
    {
        $message = "Quantity entered has to be numeric and positive.";
        $set_focus = 'quantity';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }
    
    /*
    if(strlen($MPI['debit_account']) > 0)
    {
        if(!(strlen($MPI['credit_account']) > 0))
        {
            $message = "If Debit Account is selected Credit Account should be selected too.";
            $set_focus = 'credit_account';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
        }
    }
    else{
        if(strlen($MPI['credit_account']) > 0)
        {
            $message = "If Debit Account is not selected can not select Credit Account.";
            $set_focus = 'credit_account';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
        }
    }
      */
    return array("success" => true, "message" => "");    
}

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


function save_manual_project_invoice_header(&$pi_no, $MPI)
{
    $validate = can_process_pi_header($pi_no, $MPI);   
    
    if($validate["success"] !== true) 
    {          
        if(isset($validate["focus_to"])){
            set_focus($validate["focus_to"]);
        }
        return array("success" => false, "focus_to"=>'', "message" => $validate["message"]);
    }
    
        $due_date = get_invoice_duedate($MPI['payment_terms'], $MPI['ord_date']);

    $pi_taxes = array();
    $taxes_total = $staxes_total = 0;
    $tax_group_id = $MPI['tax_group_id'];
    $tax_types_array = get_tax_group_items_as_array($tax_group_id);
    foreach ($tax_types_array as $tax_type){
        if(isset($MPI[$tax_type['tax_type_id'].'_mpi_tax']) && $MPI[$tax_type['tax_type_id'].'_mpi_tax'] > 0 && $tax_type['rate'] > 0){
            $tax_amount = $MPI[$tax_type['tax_type_id'].'_mpi_tax'];
            $a = array('tax_type_id' => $tax_type['tax_type_id'], 'tax_amount' => $tax_amount, 'suspended' => $tax_type['suspended']);
            $pi_taxes[] = $a;
            
            if($tax_type['suspended'] == 0){
                $taxes_total += $tax_amount;
            }
            else{
                $staxes_total += $tax_amount;
            }
        }
    }
    
    $project_sales_order_id = 0;
    if($MPI['project_sales_order_id'] > 0){
        $project_sales_order_id = $MPI['project_sales_order_id'];
    }
    
    $pi_no = write_manual_project_invoice_header($pi_no, $MPI['project_id'], $MPI['customer_id'],
                                        $MPI['branch_code'], $MPI['reference'], $MPI['payment_terms'],
                                        $MPI['ord_date'], $MPI['salesman_code'], 
                                        $MPI['total'], $taxes_total, $MPI['rate_include_taxes'],                                 
                                        $MPI['payment_application_id'], $MPI['payment_certificate_ref'], $MPI['payment_certificate_amount'],
                                        $due_date, '', $MPI['tax_group_id'], $pi_taxes, 
                                        $project_sales_order_id, $staxes_total);   
    
    if($pi_no > 0){
        return array("success" => true, "focus_to" => '','trans_no' => $pi_no, "message" => "Project Invoice $pi_no has been saved.");
    }
    else{
        return array("success" => false,  "focus_to" => '', 'trans_no' => '', "message" => "Could not save Project Invoice.");
    }
}

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

function save_manual_project_invoice_detail(&$pi_no, $selected_id, $MPI)
{
    $msg = can_process_pi_detail($MPI);
    if($msg["success"] !== true){
        return $msg;
    }
    
    switch ($MPI['line_type']) {
        case PILT_MAIN_ITEM:
        case PILT_SUB_ITEM:
        case PILT_DETAIL:
            $unit = $MPI['unit'];
            if($unit === '' || $unit === 0 || $unit === null){
            }else{
                $MPI['amount'] = $MPI['quantity'] * $MPI['rate'];
            }
    }
    write_manual_project_invoice_detail($pi_no, $selected_id, $MPI['line_type'], 
                                        $MPI['sequence'], $MPI['description'], date2sql($MPI['completed_date']), $MPI['unit'], 
                                        $MPI['quantity'], $MPI['rate'], $MPI['amount'], $MPI['line_comment'],
                                        $MPI['category_id'], $MPI['debit_account'], $MPI['credit_account']);
    
    return array("success" => true, "message" => "");
    
}

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



function release_for_approval_mpi($pi_no, $MPI)
{
    $msg = save_manual_project_invoice_header($pi_no, $MPI);
    if($msg['success'] !== true){
         return array("success" => false,  "focus_to" => '', 'trans_no' => '', "message" => "");
    }

    begin_transaction();
        
//    update_project_invoice_header($pi_no, $_POST['project_id'], $_POST['customer_id'], $_POST['customer_branch'], 
//            $_POST['payment_terms'], $_POST['order_date'], $due_date, $_POST['sales_person']);

//    $pih = get_project_invoice_header($pi_no);
    $pih = get_manual_project_invoice_header($pi_no);
    $items_added_tax = 0;

    $pi_total = $pih['total'] + $pih['taxes'];
    
    
    $current_user_id = $_SESSION['wa_current_user']->user;


//    $row_state = db_new_row_state($pih['row_state']);
    
    $info = approve_document(ST_PROJECT_INVOICE, $pi_no, $pih['project_id'], 
                                $pi_total, $pih['next_approval_group_id'], 
                                $current_user_id, $pih['row_state'], $pih['created_by']);

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

    if(exists_customer_trans(ST_PROJECT_INVOICE, $pi_no)){
        cancel_transaction();
        return array("success" => false, "message" => "Project Invoice $pi_no is already in the customer's transactions list.");
    }
    
    
    if($info['approval_status'] == AS_APPROVED){
        add_customer_transaction(ST_PROJECT_INVOICE, $pi_no, $pih['debtor_no'], $pih['branch_code'], 
                                        sql2date($pih['ord_date']), $pih['reference'], $pih['total'], 0,
                                        $pih['taxes'], 0, 0, 0, 
                                        0, 0, sql2date($pih['due_date']), 0, 
                                        0, 0, 0, $pih['payment_terms'], 
                                        $pih['project_id'], $pih['staxes'], $pih['tax_group_id']); 
    }
    
    commit_transaction();
    
    return array("success" => true, "focus_to" => '', "message" => $info['message']);
                    
}



function save_manual_project_invoice(&$pi_no, $selected_id, $MPI)
{
    $approval_status = 0;
    
    begin_transaction();
    
    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'];
        }
    }
    
    if(in_array($approval_status, array(AS_NEW, AS_AWAITING_APPROVAL, AS_WITH_THE_APPROVER, AS_BACK_TO_ORIGINATOR))){
        $msg = save_manual_project_invoice_header($pi_no, $MPI);
        if($msg["success"] !== true){
            cancel_transaction();
            return $msg;
        }
    }

    $msg = save_manual_project_invoice_detail($pi_no, $selected_id, $MPI);
    if($msg["success"] !== true){
        cancel_transaction();
        return $msg;
    }

    commit_transaction();
    
    return array("success" => true, 'trans_no' => $pi_no, "message" => $msg["message"]);

}





?>