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

$page_security = 'SA_MISCELLANEOUS_PROJECT_COSTS';
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 . "/includes/approval_functions.inc"); 
include_once($path_to_root . "/reporting/includes/reporting.inc");
include_once($path_to_root . "/includes/db/approval_functions_db.inc");
include_once($path_to_root . "/projects/includes/db/project_boq_item_groups_db.inc");
include_once($path_to_root . "/projects/includes/db/miscellaneous_project_cost_db.inc");
include_once($path_to_root . "/includes/project_cost_functions.inc");
//include_once($path_to_root . "/includes/references.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 = "Miscellaneous Project Costs"), false, false, "", $js);

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

$mpc_no = -1;
 
if (isset($_GET['MPC_No']))
{
    $_POST['MPC_No'] = $_GET['MPC_No'];
    set_session_variable("ST_MISCELLANEOUS_PROJECT_COST_no", $mpc_no);
}


if (isset($_GET['NewOrder']))
{
    $_POST['MPC_No'] = -1;
    set_session_variable("ST_MISCELLANEOUS_PROJECT_COST_no", $_POST['MPC_No']);
} 

if (isset($_POST['MPC_No']) && $_POST['MPC_No'] > 0){
    $mpc_no = $_POST['MPC_No'];
}
else{
    if(!isset($_POST['MPC_No']) > 0){
        $_POST['MPC_No'] = -1;
        set_session_variable("ST_MISCELLANEOUS_PROJECT_COST_no", $_POST['MPC_No']);
    }else{
        $mpc_no = get_session_variable('ST_MISCELLANEOUS_PROJECT_COST_no');
    }
}


if (isset($_GET['Processed_MPC_No'])) 
{
	//return;
        
    $trans_no = $_GET['Processed_MPC_No'];
    $trans_type = ST_MISCELLANEOUS_PROJECT_COST;
    $message = get_session_variable('ST_MISCELLANEOUS_PROJECT_COST_messages');
    clear_session_variable('ST_MISCELLANEOUS_PROJECT_COST_messages');
    
	display_notification_centered($message);
        
	display_note(print_document_link($trans_no, _("&Print this Miscellaneous Project Cost"), true, $trans_type), 0, 0);

	hyperlink_no_params("$path_to_root/projects/miscellaneous_project_costs.php", _("Create another &Miscellaneous Project Cost"));

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

	display_footer_exit();
}

//function can_delete_sc_purchase_order_details($mpc_no)
//{
//    $line_count = get_sc_purchase_orders_line_count($mpc_no);
//    if(!($line_count > 0)){
//        $message = "This is the last line. It can not be deleted.";
//        display_error($message);
//        return false;
//    }
//    
//    return true;
//
//}

function can_process_miscellaneous_pc_header($mpc_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_MISCELLANEOUS_PROJECT_COST, $mpc_no);
    if($ref_msg){
        $message = $ref_msg;
        $set_focus = 'reference';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
     
    }
    
    if($mpc_no > 0){
        $mpc = get_miscellaneous_pc_header($mpc_no);
        if(!($mpc['approval_status'] == AS_NEW || $mpc['approval_status'] == AS_WITH_THE_APPROVER || 
                $mpc['approval_status'] == AS_AWAITING_APPROVAL || $mpc['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);
        }
        
        $current_user_id = $_SESSION['wa_current_user']->user;
        $ced_msg = can_edit_document(ST_MISCELLANEOUS_PROJECT_COST, $mpc['project_id'], $mpc['next_approval_group_id'] , $current_user_id, $mpc['created_by'], $mpc_no);
        if($ced_msg['success'] !== true){
            return array("success" => false, "focus_to" => '', "message" => $ced_msg['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(!is_date($_POST['date']))
    {
        $message = "Date entered is not a valid date.";
        $set_focus = 'date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }
      
    return array("success" => true, "message" => "");    
}

 
function can_process_miscellaneous_pc_line($mpc_no)
{    
    if(!$_POST['unit_id'] > 0){
            $message = "Please select an unit.";
            $set_focus = 'unit_id';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
        
    if(!(check_num('quantity', 0.0001)))
    {
        $message = "Quantity should be greater than zero.";
        $set_focus = 'quantity';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    if(!(check_num('rate', 0.0001)))
    {
        $message = "Rate should be greater than zero.";
        $set_focus = 'rate';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    
    if(!($_POST['task_id'] > 0))
    {
        $message = "Please select a Budget.";
        $set_focus = 'task_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
    }    
    
    if(!($_POST['mpc_type_id'] > 0))
    {
        $message = "Please select a Type.";
        $set_focus = 'mpc_type_id';
        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 save_miscellaneous_pc_header(&$mpc_no)
{     
    $temp_mpc_no = $mpc_no;
            
    $mpc_no = write_miscellaneous_pc_header($mpc_no, $_POST['reference'], 
                                            $_POST['project_id'], $_POST['date'], 
                                            $_POST['approval_status']=0, 
                                            $_POST['header_comment']);   
    
    if($mpc_no > 0){
        set_session_variable("ST_MISCELLANEOUS_PROJECT_COST_no", $mpc_no);
        if($temp_mpc_no > 0){
            $message = "Miscellaneous project costs  $mpc_no has been updated.";
        }
        else{
            $message = "Miscellaneous project costs  $mpc_no has been created.";
        }
        return array("success" => true, 'trans_no' => $mpc_no, "message" => $message);
    }
    else{
        return array("success" => false, 'trans_no' => '', "message" => "Could not save Miscellaneous project cost header.");
    }
}


function save_miscellaneous_pc_detail(&$mpc_no, $selected_id)
{    
    write_miscellaneous_pc_detail($mpc_no, $selected_id,  
                                    $_POST['description'], $_POST['unit_id'],
                                    input_num('quantity'), input_num('rate'),
                                    $_POST['task_boq_group_id'], $_POST['task_id'],
                                    $_POST['mpc_type_id'], $_POST['debit_account'], $_POST['credit_account'], $_POST['comment']);                             
  
    return array("success" => true, 'trans_no' => '', "message" => " ");
}


function save_miscellaneous_pc(&$mpc_no, $selected_id)
{    
    $h_msg = can_process_miscellaneous_pc_header($mpc_no);   
    
        if($h_msg["success"] !== true) 
        {          
            if(isset($h_msg["focus_to"])){
                set_focus($h_msg["focus_to"]);
            }
            return array("success" => false, "message" => $h_msg["message"]);
        }
        
    $line_msg = can_process_miscellaneous_pc_line($mpc_no);
        if($line_msg['success'] !== true){
            if(isset($line_msg["focus_to"])){
                set_focus($line_msg["focus_to"]);
            }
            return array("success" => false, "message" => $line_msg["message"]);
        }
    
    begin_transaction();
    $msg_h = save_miscellaneous_pc_header($mpc_no);
    if($msg_h["success"] !== true){
        cancel_transaction();
        return array("success" => false, 'trans_no' => $mpc_no, "message" => $msg_h["message"]);
    }

    $msg_d = save_miscellaneous_pc_detail($mpc_no, $selected_id);
    if($msg_d["success"] !== true){
        cancel_transaction();
        return array("success" => false, 'trans_no' => $mpc_no, "message" => $msg_d["message"]);
    }
    
    commit_transaction();

    return array("success" => true, 'trans_no' => $mpc_no, "message" => $msg_h["message"]);

}


function display_miscellaneous_pc_header($mpc_no)
{
    global $approval_statuses, $Refs;
    
    if($mpc_no > 0){
        $mpc_header = get_miscellaneous_pc_header($mpc_no);
        
        $project_id = $mpc_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;
        }  
        
        $_POST['project_id'] = $mpc_header['project_id'];
    
        if(!isset($_POST['reference'])){
            $_POST['reference'] = $mpc_header['reference'];
        }

        if(!isset($_POST['date'])){
            $_POST['date'] = sql2date($mpc_header['date']);
        }
        
        if(!isset($_POST['project_description'])){
            $_POST['project_description'] = $mpc_header['project_description'];
        }
        
        if(!isset($_POST['approval_status'])){
            $_POST['approval_status'] = $mpc_header['approval_status'];
        }        
               
        if(!isset($_POST['header_comment'])){
            $_POST['header_comment'] = $mpc_header['comment'];
        }
    
    }
    else{
        
        $_POST['reference'] = $Refs->get_next(ST_MISCELLANEOUS_PROJECT_COST);
        $_POST['approval_status'] = 0;
    }
        
    start_outer_table(TABLESTYLE2, "width=30%"); // outer table
    start_table(TABLESTYLE2);  
        table_section(1, "30%");
        
        text_row("Reference:", 'reference', null, null, null);  
        
        if($mpc_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); 
        }
                     
        date_row("Date", 'date');              
       
        textarea_row("Comment:", 'header_comment', null, 25, 2);
        
        $s = get_project_trans_view_str(ST_APPROVAL_LOG, $mpc_no."&source_type_id=".ST_MISCELLANEOUS_PROJECT_COST, "Approval Status");
        label_row($s, $approval_statuses[$_POST['approval_status']]);  
     
//    end_table(1);

    end_outer_table(1); // outer table
    hidden('MPC_No', $mpc_no);
 
}


function display_miscellaneous_pc_details($selected_id, $mpc_no)
{      
    global $Ajax;              
       
    $result = get_miscellaneous_pc_details($mpc_no);     
         
    start_table(TABLESTYLE, "width=98%");
    $th = array(_("Description"), _("Units"), _('Quantity'),
                _('Rate'),_("Amount"), _("BOQ Group"), 
                _("Budget"), _("Type"), "", "");              
  
    div_start('sc_purchase_orders');
        $Ajax->activate('sc_purchase_orders');
    div_end();
    
    table_header($th);
    $k = 0; //row colour counter
      
    $total_mpc=0;
    while ($myrow = db_fetch($result))
    {
        if($selected_id != $myrow["id"]){
            alt_table_row_color($k);

            label_cell($myrow['description']);
            label_cell($myrow['unit_name']);
            label_cell($myrow['quantity'], "align=right");
            label_cell($myrow['rate'], "align=right");
            
            $amount = $myrow['quantity'] * $myrow['rate'];
            label_cell(number_format($amount, 2), "align=right");
            
            label_cell($myrow['boq_item_group_description']);
            label_cell($myrow['budget_name']);
            label_cell($myrow['miscalleneous_type']);         
//            label_cell($myrow['comment']);
          
            edit_button_cell("Edit".$myrow["id"], _("Edit"));    
            delete_button_cell("Delete".$myrow["id"], _("Delete"));

            $total_mpc += $amount;
            end_row(); 
            
            if(strlen($myrow["debit_account"]) > 0){
                $debit_account_name = "<b>Debit A/C:</b> ".$myrow["debit_account"]." - ".$myrow["debit_account_name"];
            }
            else{
//                $debit_account_name = "<b>Debit A/C:</b> Project cost account";
                $debit_account_name = "<b>Debit A/C:</b> No account selected"; 
            }
            
            if(strlen($myrow["credit_account"]) > 0){
                $credit_account_name = "<b>Credit A/C:</b> ".$myrow["credit_account"]." - ".$myrow["credit_account_name"];
            }
            else{
//                $credit_account_name = "<b>Debit A/C:</b> Project cost account";
                $credit_account_name = "<b>Debit A/C:</b> No account selected"; 
            }
            
            
            $details = $debit_account_name.spaces(5).$credit_account_name;
            
        
        
            if(strlen($details) > 0){
                alt_table_row_color($k);
                label_cell('');
                label_cell($details, "colspan=7 align=right");
                label_cell('');
                label_cell('');
                end_row();
            }

            if(strlen($myrow["comment"]) > 0){
                alt_table_row_color($k);                
                label_cell("<b>Comment:</b> ".$myrow["comment"], "colspan= 8 align=right");
                label_cell('');
                label_cell('');
                end_row(); 
            }
         
        }
    
        else{
            $total_mpc += display_miscellaneous_pc_edit_controls($selected_id, $Mode);
        }
      
    }
    
    if(!($selected_id > 0)){
       display_miscellaneous_pc_edit_controls($selected_id, $Mode);
    }
    
    start_row();
    label_cell("Total", "align=right colspan=4");
    

    label_cell("<b>".number_format($total_mpc, 2)."</b>", "align=right");
   
    end_row();
    
    end_table();
  
}


function display_miscellaneous_pc_edit_controls($selected_id, &$Mode)
{
    $line_total = 0;
    
    echo "<td colspan=8>";
    start_outer_table();
    table_section(1);

    if($selected_id > 0){
        $mpc_detail = get_miscellaneous_pc_line($selected_id);
    }

    
    if($selected_id > 0 && 
                (isset($_POST['previous_selected_id']) && $_POST['previous_selected_id'] != $selected_id)){


        $_POST['description'] = $mpc_detail['description'];
        $_POST['unit_id'] = $mpc_detail['unit'];
        $_POST['quantity'] = $mpc_detail['quantity'];
        $_POST['rate'] = $mpc_detail['rate'];       
        $_POST['task_boq_group_id'] = $mpc_detail['task_boq_group_id'];
        $_POST['task_id'] = $mpc_detail['task_id'];
        $_POST['mpc_type_id'] = $mpc_detail['mpc_type_id'];
        $_POST['comment'] = $mpc_detail['comment'];
        $_POST['debit_account'] = $mpc_detail['debit_account'];
        $_POST['credit_account'] = $mpc_detail['credit_account'];
        
        $line_total = $mpc_detail['quantity'] * $mpc_detail['rate'];
    }
    else{
        if(!isset($_POST['item_boq_group_id'])){
            $_POST['item_boq_group_id'] = 0;
        }
        if(!isset($_POST['task_boq_group_id'])){
            $_POST['task_boq_group_id'] = 0;
        }
    }


    hidden('selected_id', $selected_id );
    hidden('previous_selected_id', $selected_id );
   
  
    textarea_row("Description:", 'description', null, 30, 1);
    stock_units_list_row("Unit :", 'unit_id', null, true, 'Please select an unit');   
    amount_row("Quantity:", 'quantity');
    amount_row("Rate:", 'rate');

//    $amount = $_POST['quantity'] * $_POST['rate'];
    
//    label_row("Amount:", $amount);
    
    table_section(2);
    project_boq_item_groups_list_row("BOQ Item Group:", "task_boq_group_id", $_POST['project_id'], null, "No BOQ Item Group", true);
    group_tasks_list_row("Budget :", 'task_id', $_POST['project_id'], $_POST['task_boq_group_id'], null, _('Select a budget'));   

    value_list_row("Type:", 'mpc_type_id', 'MISCELLANEOUS_PROJECT_COST_TYPES', null, 'Please select a type', false);
    gl_all_accounts_list_row(_("Debit Account:"), 'debit_account', null, false, false, "Project cost account");
    gl_all_accounts_list_row(_("Creadit account:"), 'credit_account', null, false, false, "Project cost account");
    
    table_section(3);
    textarea_row("Comments :", 'comment', null, 30, 4);
    
    end_outer_table();
    echo "</td>";

     if ($selected_id > 0)
	{
		button_cell('UpdateItem', _("Update"),
				_('Confirm changes'), ICON_UPDATE);
		button_cell('CancelItemChanges', _("Cancel"),
				_('Cancel changes'), ICON_CANCEL);
		hidden('LineNo', $selected_id);
 		set_focus('qty');
	}
	else
	{
		submit_cells('AddItem', _("Add Item"), "colspan=2 align=center",
		    _('Add new item to document'), true);
	}

        return $line_total;

}

function can_release_miscellaneous_pc($mpc_no)
{
    $line_count = get_miscellaneous_pc_line_count($mpc_no);
    if (!($line_count > 0))
    {
        display_error("There are no miscellaneous project cost details entered. Can not release this document.");
        return false;
    }    
    
    if (!is_date_in_fiscalyear($_POST['date'])) 
    {
        display_error(_("The entered date is not in fiscal year."));
        set_focus('date');
        return false;
    } 
    
    $msg = is_accounting_period_open($_POST['date']);
    if ($msg['success'] !== true)
    {
        display_error($msg['message']);
        set_focus('date');
        return false;
    }
      
    return true;
}


function release_miscellaneous_pc($mpc_no)
{    
    $msg = can_process_miscellaneous_pc_header($mpc_no);
    if($msg['success'] !== true){
        return $msg;
    }
    
    $mpch = get_miscellaneous_pc_header($mpc_no);
    
    update_miscellaneous_pc_header($mpc_no, $_POST['reference'], 
                                    $_POST['date'], $_POST['header_comment']);
    
    $task_costs = array();
    
    $current_user_id = $_SESSION['wa_current_user']->user;
    $trans_type = ST_MISCELLANEOUS_PROJECT_COST;
        
    $result = get_miscellaneous_pc_details($mpc_no);
    while ($mpc_detail = db_fetch($result)){  
        if($mpc_detail['task_id'] > 0){
            $sti_line_amount = $mpc_detail['quantity'] * $mpc_detail['rate']; 
            if($sti_line_amount > 0){        
                add_to_task_cost($task_costs, $mpc_detail['task_id'], $sti_line_amount, $sti_line_amount, $sti_line_amount);
            }
        }
    }
    

    get_task_cost_details($task_costs);
    
          
    $info = approve_document(ST_MISCELLANEOUS_PROJECT_COST, $mpc_no, $mpch['project_id'], 
                            $task_costs, $mpch['next_approval_group_id'], 
                            $current_user_id, $mpch['row_state']);
    
    if($info['success'] !== true){
        return array("success" => $info['success'],"trans_no" => $mpc_no, "message" => $info['message']);
    }

    if($info['approval_status'] != AS_APPROVED){
        return array("success" => $info['success'], "trans_no" => $mpc_no, "message" => $info['message']);
    }
    
    $cct_msg = charge_cost_to_tasks($trans_type, $mpc_no, $task_costs, $current_user_id);
    if($cct_msg['success'] !== true)
    {
        return array("success" => $cct_msg['success'], "tran_no" => $mpc_no, "message" => $cct_msg['message']);
    }

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

function release_miscellaneous_pc_for_approval($mpc_no)
{    
    
    if(!can_release_miscellaneous_pc($mpc_no)){
        return;
    }
    
    begin_transaction();
    $rmpc_msg = release_miscellaneous_pc($mpc_no);
    if($rmpc_msg['success'] !== true){
        cancel_transaction();
        display_error($rmpc_msg['message']);
        return;
    }

    commit_transaction();
    clear_session_variable("ST_MISCELLANEOUS_PROJECT_COST_no");
    set_session_variable('ST_MISCELLANEOUS_PROJECT_COST_messages', $rmpc_msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "Processed_MPC_No=$mpc_no");
    
}

function send_miscellaneous_pc_back_to_originator($mpc_no)
{        
    $msg = can_process_miscellaneous_pc_header($mpc_no);
      if($msg['success'] !== true){
        return $msg;
    }
    
    begin_transaction();
     
    $mpch = get_miscellaneous_pc_header($mpc_no);

    $current_user_id = $_SESSION['wa_current_user']->user;

    $mpch_msg = send_back_to_document_originator(ST_MISCELLANEOUS_PROJECT_COST, $mpc_no, $mpch['project_id'],
                                    $mpch['next_approval_group_id'], $current_user_id, $mpch['row_state'], 
                                    $mpch['created_by']);
    
    if($mpch_msg['success'] !== true){
        display_error_cancel($mpch_msg['message']);
        return;
    }

    commit_transaction();
    clear_session_variable("ST_MISCELLANEOUS_PROJECT_COST_no");
    set_session_variable('ST_MISCELLANEOUS_PROJECT_COST_messages', $mpch_msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "Processed_MPC_No=$mpc_no");
            
}


function reject_miscellaneous_pc($mpc_no)
{
    $msg = can_process_miscellaneous_pc_header($mpc_no);
        if($msg['success'] !== true){
            return $msg;
    }
    
    begin_transaction();
    
    $mpch = get_miscellaneous_pc_header($mpc_no);

    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $rj_msg = reject_document(ST_MISCELLANEOUS_PROJECT_COST, $mpc_no, $mpch['project_id'],
                    $mpch['next_approval_group_id'], $current_user_id, $mpch['row_state']);
    
    if($rj_msg['success'] !== true){
        display_error_cancel($rj_msg['message']);
        return;
    }

    commit_transaction();
    clear_session_variable("ST_MISCELLANEOUS_PROJECT_COST_no");
    set_session_variable('ST_MISCELLANEOUS_PROJECT_COST_messages', $rj_msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "Processed_MPC_No=$mpc_no");
 }

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


if(isset($_POST['Update_Release_Miscellaneous_PC']))
{
    release_miscellaneous_pc_for_approval($mpc_no);
}


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

    send_miscellaneous_pc_back_to_originator($mpc_no);        
} 

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

    reject_miscellaneous_pc($mpc_no);        
}


if(isset($_POST['Save_Miscellaneous_PC'])){
        
    $h_msg = can_process_miscellaneous_pc_header($mpc_no);   
    
    if($h_msg["success"] !== true){          
        if(isset($h_msg["focus_to"])){
            set_focus($h_msg["focus_to"]);
        }
        display_error($h_msg['message']);
    }
    else{   
        begin_transaction();
        $msg = save_miscellaneous_pc_header($mpc_no);    
        if($msg['success'] !== true){
            cancel_transaction();
            display_error($msg['message']);
        }
        else{
            commit_transaction();
            display_notification($msg['message']);
        }

    }

}


if(isset($_POST['AddItem']) || isset($_POST['UpdateItem'])){
        
    $msg = save_miscellaneous_pc($mpc_no, $selected_id);
    
    if($msg['success'] !== true){
        display_error($msg['message']);
    }
    else{
        $_POST['MPC_No'] = $msg['trans_no'];
        display_notification($msg['message']);
       // display_notification("Taxes have been recalculated and updated.");
        $Mode = 'RESET';
    }

}


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

    $selected_id = -1;
}


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



if ($Mode == 'Delete')
{
    // Just check for document is editable
    $h_msg = can_process_miscellaneous_pc_header($mpc_no);            
    if($h_msg["success"] !== true) 
    {          
        if(isset($h_msg["focus_to"])){
            set_focus($h_msg["focus_to"]);
        }
        display_error($h_msg["message"]);
    }
    else{
        begin_transaction();
        $recs = delete_miscellaneous_pc_detail($mpc_no, $selected_id);
        if($recs == 1){
            display_notification("Miscellaneous project cost detail been deleted.");
        }
        commit_transaction();
    }

    $Mode = 'RESET';
}

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


display_miscellaneous_pc_header($mpc_no);   

if($mpc_no > 0){
    submit_center_first('Save_Miscellaneous_PC', _("Save"), '', 'default');
   
    br(2);
    
    submit_center_first('Update_Release_Miscellaneous_PC', "Release for Approval", '', 'default');
    submit('Back_To_Originator_Miscellaneous_PC', 'Back To Originator', true, '', 'default');
    submit_center_last('Reject_Miscellaneous_PC', "Reject", '', 'default');	
}

br(2);

//------------------------------------------------------------------------------------------------------------
               
display_miscellaneous_pc_details($selected_id, $mpc_no);
  
//-----------------------------------------------------------------------------------------------------------

br();

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



?>
