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

$page_security = 'SA_PROJECT_CREDIT_NOTE';
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 . "/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 . "/projects/includes/db/project_credit_notes_db.inc");
include_once($path_to_root . "/projects/includes/db/projects_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 = "Project Credit Notes"), false, false, "", $js);

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


$pcn_no = -1;

if (isset($_GET['PCN_No']))
{
    $_POST['PCN_No'] = $_GET['PCN_No'];
    set_session_variable("ST_PROJECT_CREDIT_NOTE_pcn_no", $_POST['PCN_No']);
}

if (isset($_GET['NewOrder']))
{
    $_POST['PCN_No'] = -1;
    set_session_variable("ST_PROJECT_CREDIT_NOTE_pcn_no", $_POST['PCN_No']);
}        
        
if (isset($_POST['PCN_No']) && $_POST['PCN_No'] > 0){
    set_session_variable("ST_PROJECT_CREDIT_NOTE_pcn_no", $_POST['PCN_No']);
}
else{
    if(!isset($_POST['PCN_No'])){
        $_POST['PCN_No'] = -1;
        set_session_variable("ST_PROJECT_CREDIT_NOTE_pcn_no", $_POST['PCN_No']);
    }
}

$pcn_no = get_session_variable('ST_PROJECT_CREDIT_NOTE_pcn_no'); 

if (isset($_GET['Released_ID'])) 
{
	//return;
        
    $trans_no = $_GET['Released_ID'];
    $trans_type = ST_PROJECT_CREDIT_NOTE;
    $message = get_session_variable('project_credit_note_messages');
    clear_session_variable('project_credit_note_messages');
    
	display_notification_centered($message);
        
	display_note(print_document_link($trans_no, _("&Print this Project Credit Note"), true, $trans_type), 0, 0);

	hyperlink_no_params("$path_to_root/projects/project_credit_notes.php", _("Create another &Project Credit Note"));

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

	display_footer_exit();
}


function can_process_pcn_header($pcn_no)
{
    global $Refs;
            
    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_PROJECT_CREDIT_NOTE, $pcn_no);
    if($ref_msg){
        $message = $ref_msg;
        $set_focus = 'reference';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);   
    }
    
    if($pcn_no > 0){
        $pcn = get_project_credit_note_header($pcn_no);
        if(!($pcn['approval_status'] == AS_NEW || $pcn['approval_status'] == AS_WITH_THE_APPROVER || 
                $pcn['approval_status'] == AS_AWAITING_APPROVAL || $pcn['approval_status'] == AS_BACK_TO_ORIGINATOR)){
            $message = ("This document status does not allow further updating.");
            $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['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($_POST['ord_date']))
    {
        $message = "Date entered is not a valid date.";
        $set_focus = 'ord_date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }
    
    if (!is_date_in_fiscalyear($_POST['ord_date'])) 
    {
        $message = (_("The entered date is not in fiscal year."));         
        $set_focus = 'ord_date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);      
    } 
    
    $msg = is_accounting_period_open($_POST['ord_date'], true);
    if ($msg['success'] !== true)
    {
        $message = ($msg['message']);         
        $set_focus = 'ord_date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);      
    }
    
    
      if($pcn_no > 0){        
        $current_user_id = $_SESSION['wa_current_user']->user;
        $ced_msg = can_edit_document(ST_PROJECT_CREDIT_NOTE, $pcn['project_id'], $pcn['next_approval_group_id'] , $current_user_id, $pcn['created_by'], $pcn_no);
        if($ced_msg['success'] !== true){
            return array("success" => false, "focus_to" => '', "message" => $ced_msg['message']);
        }
    } 
    
      
    return array("success" => true, "message" => "");    
}


function can_process_pcn_detail()
{    
    global $project_invoice_line_types;
    
    if($_POST['line_type'] == 0 || $_POST['line_type'] == 2 || $_POST['line_type'] == 5){
        if(!is_date($_POST['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_num('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($_POST['debit_account']) > 0)
    {
        if(!(strlen($_POST['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($_POST['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 _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 date2sql($_POST['completed_date']);      
    }
    else{  
        return '';    
    }
}


function save_project_credit_note_header(&$pcn_no)
{
    $validate = can_process_pcn_header($pcn_no);   
    
    if($validate["success"] !== true) 
    {          
        if(isset($validate["focus_to"])){
            set_focus($validate["focus_to"]);
        }
        return array("success" => false, "message" => $validate["message"]);
    }
    
    $pi_taxes = array();
    $taxes_total = $staxes_total = 0;
    $tax_group_id = $_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){
            $tax_amount = input_num($tax_type['tax_type_id'].'_mpi_tax');
            $a = array('tax_type_id' => $tax_type['tax_type_id'], 
                        'tax_amount' => $tax_amount, 
                        'tax_type_name' => $tax_type['tax_type_name'],
                        'tax_rate' => $tax_type['rate'],
                        'suspended' => $tax_type['suspended'] );
            $pi_taxes[] = $a;
            
            if($tax_type['suspended'] == 0){
                $taxes_total += $tax_amount;
            }
            else{
                $staxes_total += $tax_amount;
            }
        }
    }
    
    
    $pcn_no = write_project_credit_note_header($pcn_no, $_POST['project_id'], $_POST['debtor_no'],
                                                $_POST['branch_code'], $_POST['reference'], 
                                                $_POST['ord_date'], $_POST['salesman_code'], 
                                                input_num('total'), $taxes_total, $_POST['rate_include_taxes'],                          
                                                $_POST['tax_group_id'], $pi_taxes,
                                                $_POST['project_invoice_id'], $_POST['comment'], $staxes_total);   
    
    if($pcn_no > 0){
        set_session_variable("ST_PROJECT_CREDIT_NOTE_pcn_no", $pcn_no);
        return array("success" => true, 'trans_no' => $pcn_no, "message" => "Project Credit Note $pcn_no has been saved.");
    }
    else{
        return array("success" => false, 'trans_no' => '', "message" => "Could not save Project Credit Note.");
    }
}


function save_project_credit_note_detail(&$pcn_no, $selected_id)
{
    $msg = can_process_pcn_detail();
    if($msg["success"] !== true){
        return $msg;
    }
    
    write_project_credit_note_detail($pcn_no, $selected_id, $_POST['line_type'], 
                                        input_num('sequence'), $_POST['description'], _get_completed_date(), $_POST['unit'], 
                                        input_num('quantity'), input_num('rate'), input_num('amount'), $_POST['line_comment'],
                                        $_POST['category_id'], $_POST['debit_account'], $_POST['credit_account']);
    
    return array("success" => true, "message" => "");
    
}


function save_project_credit_note(&$pcn_no, $selected_id)
{
    begin_transaction();
    
    $temp_pcn_no = $pcn_no;
    
    $msg = save_project_credit_note_header($pcn_no);
    if($msg["success"] !== true){
        cancel_transaction();
        return $msg;
    }

    $msg = save_project_credit_note_detail($pcn_no, $selected_id);
    if($msg["success"] !== true){
        cancel_transaction();
        return $msg;
    }

    commit_transaction();
    
    if($temp_pcn_no > 0){
        $message = "Project Credit Note $pcn_no has been updated.";
    }
    else{
        $message = "Project Credit Note $pcn_no has been created.";
    }
    return array("success" => true, 'trans_no' => $pcn_no, "message" => $message);

}

function display_project_credit_note_header($pcn_no)
{
    global $Refs;
    
    if($pcn_no>0){
        $pcn_header = get_project_credit_note_header($pcn_no);
    
        $project_id = $pcn_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'] = $pcn_header['project_id'];
        }
     

        if(!(isset($_POST['debtor_no']) && $_POST['debtor_no'] > 0)){
            $_POST['debtor_no'] = $pcn_header['debtor_no'];
        }        
        
        if(!isset($_POST['customer_branch'])){
            $_POST['customer_branch'] = $pcn_header['branch_code'];
        }
        if(!isset($_POST['reference'])){
            $_POST['reference'] = $pcn_header['reference'];
        }
        
        if(!isset($_POST['project_description'])){
            $_POST['project_description'] = $pcn_header['project_description'];
        }

        if(!isset($_POST['ord_date'])){
            $_POST['ord_date'] = sql2date($pcn_header['ord_date']);
        }
        if(!isset($_POST['salesman_code'])){
            $_POST['salesman_code'] = $pcn_header['salesman_code'];
        }
        if(!isset($_POST['total'])){
            $_POST['total'] = $pcn_header['total'];
        }
        if(!isset($_POST['taxes'])){
            $_POST['taxes'] = $pcn_header['taxes'];
        }
        if(!isset($_POST['comment'])){
            $_POST['comment'] = $pcn_header['comment'];
        }
        
        if(!isset($_POST['project_invoice_id'])){
            $_POST['project_invoice_id'] = $pcn_header['project_invoice_id'];
        }
      
        if(!isset($_POST['tax_group_id'])){
            $_POST['tax_group_id'] = $pcn_header['tax_group_id'];
        }
               
        $_POST['approval_status'] = $pcn_header['approval_status'];
    }
    else{  
        $_POST['reference'] = $Refs->get_next(ST_PROJECT_CREDIT_NOTE);            
        $_POST['approval_status'] = 0;
    }
        
    start_outer_table(TABLESTYLE2, "width=75%"); // outer table
    start_table(TABLESTYLE2);  
        table_section(1, "35%");
            text_row("Reference:", 'reference', null, null, null);  
            
            if($pcn_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); 
            }
         
            $project = get_project($_POST['project_id']);
            if(!(isset($_POST['debtor_no']) && $_POST['debtor_no'] > 0)){
                $_POST['debtor_no'] = $project['customer_id']; 
            } 

            if($pcn_no > 0){
                customer_list_row("Customer:", 'debtor_no', null, 'Please select a customer', true);
            }
            else{
                customer_list_row("Customer:", 'debtor_no', null, 'Please select a customer', true);
            } 

            customer_branches_list_row("Branch:", $_POST['debtor_no'], 'branch_code', null, false, false, false);        
                       
//        table_section(2, "35%");
            
            date_row("Order Date:", 'ord_date');
     
            sales_persons_list_row("Sales Person:", 'salesman_code', null);
        
        table_section(2, "35%");
            
       
        project_invoices_list_row("Project Invoice:", 'project_invoice_id', $_POST['project_id'], null, '', false);
        
        textarea_row("Comment:", 'comment', null, 20, 2);
            
        global $approval_statuses;
        $s = get_project_trans_view_str(ST_APPROVAL_LOG, $pcn_no."&source_type_id=".ST_PROJECT_CREDIT_NOTE, "Approval Status");
        label_row($s,$approval_statuses[$_POST['approval_status']]);

//    end_table(1);

//    end_outer_table(1); // outer table
    hidden('PCN_No', $pcn_no);
        


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

            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['debtor_no'], $_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($pcn_no, $_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_outer_table(1);
    
    if($_POST['debtor_no'] != $project['customer_id']){
        $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);
    }
    

}

function display_selected_tax_types($pcn_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_project_credit_note_tax_type_amount($pcn_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_project_credit_note_details($pcn_no)
{  
    global $project_invoice_line_types;    
          
    $result = get_project_credit_note_details($pcn_no);  
    
                              
    start_table(TABLESTYLE, "width=95%");
    $th = array(_('Seq.'),_('Details'), _('Date'),
                _('Unit'), _('Quantity'),_('Rate'), _('Amount'),
                _('Category'), "Debit Account", "Credit Account", "", "");              

    table_header($th);
    $k = 0; //row colour counter
   // $total = 0;
    
    while ($myrow = db_fetch($result))
    {
        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"]);
                label_cell(number_format($myrow["quantity"],3), "align=right");
                label_cell(number_format($myrow["rate"],2), "align=right");
                
                if($myrow["unit_name"] != ''){
                    $amount = $myrow["quantity"] * $myrow["rate"];
                    label_cell(number_format($amount, 2), "align=right");                   
                }else{
                    label_cell(number_format($myrow["amount"], 2), "align=right" . spaces(10));                   
                }
                             
                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"]);
                label_cell(number_format($myrow["quantity"],3), "align=right");
                label_cell(number_format($myrow["rate"],2), "align=right");
                              
                if($myrow["unit_name"] != ''){
                    $amount = $myrow["quantity"] * $myrow["rate"];
                    label_cell(number_format($amount, 2), "align=right");                   
                }else{
                    label_cell(number_format($myrow["amount"], 2), "align=right" . spaces(10));                   
                }
               
                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"]);
                label_cell(number_format($myrow["quantity"],3), "align=right");
                label_cell(number_format($myrow["rate"],2), "align=right");
                
                if($myrow["unit_name"] != ''){
                    $amount = $myrow["quantity"] * $myrow["rate"];
                    label_cell(number_format($amount, 2), "align=right");
                }else{
                    label_cell(number_format($myrow["amount"], 2), "align=right" . spaces(10));
                }
                
              
                break;
            case PILT_FINAL_TOTAL:
                label_cell("");
                label_cell("");
                label_cell("");
                label_cell("");
                amount_cell($myrow["amount"], true);
                break;
        }  

        label_cell($myrow["category_name"]);
        
        if($myrow['debit_account'] > 0){
            label_cell($myrow["debit_account"]." - ".$myrow["debit_account_name"]);
        }else{
            label_cell('');
        }
        
        if($myrow['credit_account'] > 0){
            label_cell($myrow["credit_account"]." - ".$myrow["credit_account_name"]);  
        }else{
            label_cell('');
        }

        edit_button_cell("Edit".$myrow["id"], _("Edit"));    
        delete_button_cell("Delete".$myrow["id"], _("Delete"));  
                
        end_row();  
        
        if(strlen($myrow["line_comment"]) > 0){
            alt_table_row_color($k);
            label_cell('');
            label_cell($myrow["line_comment"], 'colspan=9');
            label_cell('');
            label_cell('');
            end_row();
        }
      
       }       
      
    }

function display_project_credit_note_edit_controls($selected_id, &$Mode)
{
    if ($Mode =='Edit')   
    {
        $myrow = get_project_credit_note_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);
    
    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;
    }
    
    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(_("Creadit account:"), 'credit_account', null, false, false, "");

    textarea_row("Line Comment:", 'line_comment', null, 50, 4);
      
    end_table(1);
    div_end();

}


function can_release_pcn($pcn_no)
{
    $set_focus = '';
    
    $line_count = get_project_credit_note_line_count($pcn_no);
    if (!($line_count > 0))
    {
        $message = ("There are no project credit note details entered. Can not release this document.");        
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);    
    }
    
    return array("success" => true, "focus_to" => $set_focus, "message" => '');    
}

function release_for_approval($pcn_no)
{        
//    $msg = can_process_pcn_header($pcn_no);
//    if($msg['success'] !== true){
//        return $msg;
//    }


    begin_transaction();   
    
    $msg = save_project_credit_note_header($pcn_no);
    if($msg['success'] !== true){
        cancel_transaction();
        return $msg;
    }
    
    $pcnh = get_project_credit_note_header($pcn_no);
    
    update_project_credit_note_header($pcn_no, $_POST['debtor_no'], $_POST['branch_code'], $_POST['reference'],
                                    $_POST['ord_date'], $_POST['salesman_code'], $pcnh['total'], $pcnh['taxes'], 
                                    $pcnh['rate_include_taxes'], $pcnh['tax_group_id'], 
                                    $_POST['project_invoice_id'], $_POST['comment'], $pcnh['staxes']);

    $items_added_tax = 0;

    $pcn_total = $pcnh['total'] + $pcnh['taxes'];
    
    
    $current_user_id = $_SESSION['wa_current_user']->user;

    
    $info = approve_document(ST_PROJECT_CREDIT_NOTE, $pcn_no, $pcnh['project_id'], 
                            $pcn_total, $pcnh['next_approval_group_id'], 
                            $current_user_id, $pcnh['row_state'], $pcnh['created_by']);

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

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

function send_pi_back_to_originator($pcn_no)
{
   $msg = can_process_pcn_header($pcn_no);
    if($msg['success'] !== true){
        return $msg;
    }
    
    begin_transaction();
    
    $pcn_h = get_project_credit_note_header($pcn_no);

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

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

function reject_pi($pcn_no)
{
    $msg = can_process_pcn_header($pcn_no);
    if($msg['success'] !== true){
        return $msg;
    }

    begin_transaction();
    $pcn_header = get_project_credit_note_header($pcn_no);

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

}

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


if (isset($_POST['Release_PCN'])){
     
    $crmpi_msg = can_release_pcn($pcn_no);
    if($crmpi_msg['success'] !== true){
        display_error($crmpi_msg['message']);
    }
    
    $release_msg = release_for_approval($pcn_no);
    if($release_msg['success'] !== true){
        display_error($release_msg['message']);
    }
    else{
        new_doc_date($_POST['ord_date']);
        set_session_variable('project_credit_note_messages', $release_msg['message']);
        meta_forward($_SERVER['PHP_SELF'], "Released_ID=$pcn_no");
    }
    
} 

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

    $sent_back_msg = send_pi_back_to_originator($pcn_no);
    if($sent_back_msg['success'] !== true){
        display_error($sent_back_msg['message']);
    }
    else{
        new_doc_date($_POST['ord_date']);
        set_session_variable('project_credit_note_messages', $sent_back_msg['message']);
        meta_forward($_SERVER['PHP_SELF'], "Released_ID=$pcn_no");
    }
        
} 


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

    $reject_msg = reject_pi($pcn_no);
        if($reject_msg['success'] !== true){
        display_error($reject_msg['message']);
    }
    else{
        new_doc_date($_POST['ord_date']);
        set_session_variable('project_credit_note_messages', $reject_msg['message']);
        meta_forward($_SERVER['PHP_SELF'], "Released_ID=$pcn_no");
    }
        
} 


if(isset($_POST['Save_PCN_Header'])){
        
    begin_transaction();
    $msg = save_project_credit_note_header($pcn_no);
    
    if($msg['success'] !== true){
        cancel_transaction();
        display_error($msg['message']);
    }
    else{
        commit_transaction();
        $_POST['PCN_No'] = $msg['trans_no'];
        display_notification($msg['message']);
        $Mode = 'RESET';
    }

}


if(isset($_POST['Add_PCN_Item']) || isset($_POST['Update_PCN_Item'])){
        
    $msg = save_project_credit_note($pcn_no,$selected_id);
    
    if($msg['success'] !== true){
        display_error($msg['message']);
    }
    else{
        $_POST['PCN_No'] = $msg['trans_no'];
        display_notification($msg['message']);
        $Mode = 'RESET';
    }
}


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

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

if ($Mode == 'Delete')
{
        $recs = delete_project_credit_note_item($selected_id);
        
        if($recs == 1){
                display_notification(_("Project credit note item has been deleted."));
        }
        else{
                display_error(_("Project credit note 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_project_credit_note_header($pcn_no);   

if($pcn_no > 0){
    submit_center_first('Save_PCN_Header', _("Save"), '', 'default');    
}


if($pcn_no > 0 && !($selected_id > 0)){
    br(2); 
    submit_center_first('Release_PCN', "Release for Approval", '', 'default');
    submit('Back_To_Originator_PCN', 'Back To Originator', true, '', 'default');
    submit_center_last('Reject_PCN', "Reject", '', 'default');	
}

br(2);

//------------------------------------------------------------------------------------------------------------
         
display_project_credit_note_details($pcn_no);


end_table(1);
//-----------------------------------------------------------------------------------------------------------

display_project_credit_note_edit_controls($selected_id, $Mode);

if($selected_id > 0){
    submit_center_first('Update_PCN_Item', _("Update"), '', 'default');
    submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
}
else{  
    submit_center_first('Add_PCN_Item', _("ADD"), '', 'default');
    submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
}
 
br();


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


?>
