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

function display_monthly_pc_departments($mpc_no)
{      
    global $Ajax; 
    global $monthly_project_costs_base_totals, $monthly_project_costs_distribution_types;
       
    $result = get_monthly_project_costs_departments($mpc_no);    

         
    start_table(TABLESTYLE, "width=80%");
    $th = array(_("Department"), "Total Of", _("Base Value"), "Distributed On",  _('Distributed Total'), "Department Total Cost", "", "");              
  
    div_start('sc_purchase_orders');
        $Ajax->activate('sc_purchase_orders');
    div_end();
    
    table_header($th);
    $k = 0; //row colour counter
      
    $total_calculated_value = $total_applied_value = $total_cost = 0;
    while ($myrow = db_fetch($result))
    {

            alt_table_row_color($k);

            label_cell($myrow['department_name']);
            
            if(isset($myrow['id']) && $myrow['id'] > 0){
                label_cell($monthly_project_costs_base_totals[$myrow['base_total_type']]);
                label_cell(number_format($myrow['calculated_value'], 2), "align=right");
                label_cell($monthly_project_costs_distribution_types[$myrow['distribution_type']]);
                label_cell(number_format($myrow['applied_value'], 2), "align=right");
                label_cell(number_format($myrow['total'], 2), "align=right");
                
                delete_button_cell("Delete".$myrow['department_id'], _("Delete"));
            }
            else{
                label_cell('');
                label_cell('');
                label_cell('');
                label_cell('');
                label_cell('');
                label_cell('');
            }    
            $edit_link = get_journal_trans_view_str(ST_MONTHLY_PROJECT_COSTS_DETAIL_EDIT, $mpc_no."|".$myrow["lv_department_id"],"Details");
            label_cell($edit_link, "align=center");   

            $total_calculated_value += $myrow['calculated_value'];
            $total_applied_value += $myrow['applied_value'];
            $total_cost += $myrow['total'];
            end_row();         
        }
    
        
      

    
    start_row();
    label_cell("Totals", "colspan=2 align=right");
    label_cell("<b>".number_format($total_calculated_value, 2)."</b>", "align=right");
    label_cell("<b>".number_format($total_applied_value, 2)."</b>", "colspan=2 align=right");
    label_cell("<b>".number_format($total_cost, 2)."</b>", "align=right");
    label_cell("", "colspan=2");
    
    end_row();
    
    end_table();
  
}



function display_monthly_project_costs_details($selected_id, $mpc_no)
{      
    global $Ajax;              
       
    $result = get_monthly_project_costs_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 || strlen($myrow["credit_account"]) > 0){
                $details = "<b>Debit A/C:</b> ".$myrow["debit_account"]." - ".$myrow["debit_account_name"];
                $details .= spaces(5)."<b>Credit A/C:</b> ".$myrow["credit_account"]." - ".$myrow["credit_account_name"];
            }
            else{
                $details = "";
            }
        
        
            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_monthly_project_costs_edit_controls($selected_id, $Mode);
        }
      
    }
    
    if(!($selected_id > 0)){
       display_monthly_project_costs_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 save_monthly_project_costs(&$mpc_no, $selected_id)
{    
    if($mpc_no > 0){
        $mpch = get_monthly_project_costs_header_record($mpc_no);
        $row_state = $mpch['row_state'];
    }
    else{
        $row_state = 0;
    }
    
    $h_msg = can_process_monthly_project_costs_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"]);
    }
        
    
    begin_transaction();
    $msg_h = save_monthly_project_costs_header($mpc_no, $row_state);
    if($msg_h["success"] !== true){
        cancel_transaction();
        return array("success" => false, 'trans_no' => $mpc_no, "message" => $msg_h["message"]);
    }

    commit_transaction();

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

}



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

    if($selected_id > 0){
        $mpc_detail = get_monthly_project_costs_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, "");
    gl_all_accounts_list_row(_("Creadit account:"), 'credit_account', null, false, false, "");
    
    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",
		    _('Add new item to document'), true);
	}

        return $line_total;

}




function display_monthly_project_costs_header($mpc_no)
{
    global $approval_statuses, $Refs, $monthly_project_costs_base_totals, $monthly_project_costs_distribution_types;
    
    if($mpc_no > 0){
        $mpc_header = get_monthly_project_costs_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'];
        }
        
        if(!isset($_POST['base_total_type'])){
            $_POST['base_total_type'] = $mpc_header['base_total_type'];
        }
        
        if(!isset($_POST['distribution_type'])){
            $_POST['distribution_type'] = $mpc_header['distribution_type'];
        }
        
        if(!isset($_POST['month_id'])){
            $_POST['month_id'] = $mpc_header['month_id'];
        }
        
        if(!isset($_POST['scheduled_total'])){
            $_POST['scheduled_total'] = $mpc_header['scheduled_total'];
        }
    
    }
    else{
        $_POST['reference'] = $Refs->get_next(ST_MONTHLY_PROJECT_COSTS);
        $_POST['approval_status'] = 0;
        $_POST['total'] = 0;
        
        if(!isset($_POST['base_total_type'])){
            $_POST['base_total_type'] = 0;
        }
        
        if(!isset($_POST['distribution_type'])){
            $_POST['distribution_type'] = 0;
        }
    }
        
    start_outer_table(TABLESTYLE2, "width=70%"); // outer table
    start_table(TABLESTYLE2);  
        table_section(1, "50%");

            text_row("Reference:", 'reference', null, null, null);  

            months_list_row("Month", "month_id");

            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');              

        table_section(2, "30%");
            textarea_row("Comment:", 'header_comment', null, 25, 2);

            $s = get_project_trans_view_str(ST_APPROVAL_LOG, $mpc_no."&source_type_id=".ST_MONTHLY_PROJECT_COSTS, "Approval Status");
            label_row($s, $approval_statuses[$_POST['approval_status']]);      
            
            
        table_section(3, "30%");

            custom_values_list_row("Total Of:", 'base_total_type', $monthly_project_costs_base_totals, null, false, true);
            custom_values_list_row("Distribute On:", 'distribution_type', $monthly_project_costs_distribution_types, null, false, true);
            amount_row("Scheduled Total:", 'scheduled_total');
            
        
    end_table(0);

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


function reject_monthly_project_costs($mpc_no)
{
    $msg = can_process_monthly_project_costs_header($mpc_no);
        if($msg['success'] !== true){
            return $msg;
    }
    
    begin_transaction();
    
    $mpch = get_monthly_project_costs_header($mpc_no);

    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $rj_msg = reject_document(ST_MONTHLY_PROJECT_COSTS, $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_MONTHLY_PROJECT_COST_no");
    set_session_variable('ST_MONTHLY_PROJECT_COST_messages', $rj_msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "Processed_MPC_No=$mpc_no");
 }


 function send_monthly_project_costs_back_to_originator($mpc_no)
{        
    $msg = can_process_monthly_project_costs_header($mpc_no);
      if($msg['success'] !== true){
        return $msg;
    }
    
    begin_transaction();
     
    $mpch = get_monthly_project_costs_header($mpc_no);

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

    $mpch_msg = send_back_to_document_originator(ST_MONTHLY_PROJECT_COSTS, $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_MONTHLY_PROJECT_COST_no");
    set_session_variable('ST_MONTHLY_PROJECT_COST_messages', $mpch_msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "Processed_MPC_No=$mpc_no");
            
}


function release_monthly_project_costs_for_approval($mpc_no)
{    
    $mpch = get_monthly_project_costs_header_record($mpc_no);
    $row_state = $mpch['row_state'];
    
    $h_msg = can_process_monthly_project_costs_header($mpc_no);
    if($h_msg["success"] !== true){          
        return $h_msg;
    }
    
    begin_transaction();
    $msg_h = save_monthly_project_costs_header($mpc_no, $row_state);
    if($msg_h["success"] !== true){
        cancel_transaction();
        return array("success" => false, 'trans_no' => $mpc_no, "message" => $msg_h["message"]);
    }
    
    $crmpc_msg = can_release_monthly_project_costs($mpc_no);
    if($crmpc_msg["success"] !== true){     
        cancel_transaction();
        return array("success" => false, 'trans_no' => $mpc_no, "message" => $crmpc_msg["message"]);
    }

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

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


function release_monthly_project_costs($mpc_no)
{    
    $current_user_id = $_SESSION['wa_current_user']->user;
    $trans_type = ST_MONTHLY_PROJECT_COSTS;
    $mpch = get_monthly_project_costs_header($mpc_no);
    
    $info = approve_document($trans_type, $mpc_no, $mpch['project_id'], 
                        $mpch['total'], $mpch['next_approval_group_id'], 
                        $current_user_id, $mpch['row_state']);

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

    $result = get_monthly_project_costs_all_departments_details($mpc_no);
    while ($mpc_detail = db_fetch($result)){  
        if($mpc_detail['task_id'] > 0){
            $line_cost = $mpc_detail['value']; 
            if($line_cost > 0){        
                add_to_task_cost($task_costs, $mpc_detail['task_id'], $line_cost, $line_cost, $line_cost);
            }
        }
    }

    get_task_cost_details($task_costs);    

    $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 can_release_monthly_project_costs($mpc_no)
{
    $mpch = get_monthly_project_costs_header_record($mpc_no);
    
    $line_count = get_monthly_project_costs_line_count($mpc_no);
    if(!($line_count > 0)){
        $message = ("There are no monthly project cost details entered. Can not release this document.");
        return array("success" => false, "set_focus" => '', "message" => $message);
    }
      
    $details_total = get_monthly_project_costs_all_departments_details_total($mpc_no);
    if($mpch['scheduled_total'] != $details_total){
        $message = ("Scheduled total ".number_format($mpch['scheduled_total'],2)." and total of all the detail lines ".number_format($details_total,2)." are different. Can not release this document.");
        return array("success" => false, "set_focus" => '', "message" => $message);
    }
    return array("success" => true, "message" => "");
}


function save_monthly_project_costs_detail(&$mpc_no, $selected_id)
{    
    write_monthly_project_costs_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_monthly_project_costs_header(&$mpc_no, $row_state)
{     
    $temp_mpc_no = $mpc_no;
            
    $mpc_no = write_monthly_project_costs_header($mpc_no, $_POST['reference'], 
                                            $_POST['project_id'], $_POST['month_id'], date2sql($_POST['date']), 
                                            $_POST['base_total_type'], $_POST['distribution_type'],
                                            $_POST['header_comment'], input_num('scheduled_total'), $row_state);   
    
    if($mpc_no > 0){
        set_session_variable("ST_MONTHLY_PROJECT_COST_no", $mpc_no);
        if($temp_mpc_no > 0){
            $message = "Monthly project costs  $mpc_no has been updated.";
        }
        else{
            $message = "Monthly 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 Monthly project cost header.");
    }
}

function can_process_monthly_project_costs_header($mpc_no)
{
    global $Refs;
     
    if($mpc_no > 0){
        $mpc = get_monthly_project_costs_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_MONTHLY_PROJECT_COSTS, $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(!$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_MONTHLY_PROJECT_COSTS, $mpc_no);
    if($ref_msg){
        $message = $ref_msg;
        $set_focus = 'reference';
        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['month_id'] > 0))
    {
        $message = "Please select a month.";
        $set_focus = 'month_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);        
    }
      
    if(!check_num('scheduled_total', 0.00001))
    {
        $message = "Sheduled total should be numeric and greater than zero.";
        $set_focus = 'scheduled_total';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }
    
    return array("success" => true, "message" => "");    
}

 
function can_delete_monthly_project_costs_department($mpch)
{
    if(!($mpch['approval_status'] == AS_NEW || $mpch['approval_status'] == AS_WITH_THE_APPROVER || 
            $mpch['approval_status'] == AS_AWAITING_APPROVAL || $mpch['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_MONTHLY_PROJECT_COSTS, $mpch['project_id'], $mpch['next_approval_group_id'] , $current_user_id, $mpch['created_by'], $mpch['id']);
    if($ced_msg['success'] !== true){
        return array("success" => false, "focus_to" => '', "message" => $ced_msg['message']);
    }        
     
    return array("success" => true, "message" => "");    
}


function delete_monthly_project_costs_department_detais($mpc_no, $department_id)
{
    $mpch = get_monthly_project_costs_header_record($mpc_no);
    $old_row_state = $mpch['row_state'];
    
    $cdmpcd_msg = can_delete_monthly_project_costs_department($mpch);            
    if($cdmpcd_msg["success"] !== true){          
        return $cdmpcd_msg;
    }

    begin_transaction();
    $result = get_department_projects($department_id);
    while ($mpc_detail = db_fetch($result)) { 
        delete_monthly_project_costs_detail($mpc_no, $mpc_detail['project_id']);
    }
    
    $recs = delete_monthly_project_costs_department($mpc_no, $department_id);
    if($recs != 1){
        cancel_transaction();
        return array("success" => false, "message" => "Could not delete monthly project costs department."); 
    }
    
    $mpc_total = get_monthly_project_costs_departments_total($mpc_no);
    
    $n = update_monthly_project_costs_header_total($mpc_no, $mpc_total, $old_row_state);
    if($n != 1){
        cancel_transaction();
        return array("success" => false, "message" => "Another user has updated this monthly project costs."); 
    }

    commit_transaction();
    return array("success" => true, "message" => "Monthly project costs department has been deleted."); 
      
}

?>