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

$page_security = 'SA_PROJECT_PAY_APP';
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 . "/includes/project_cost_functions.inc");
include_once($path_to_root . "/reporting/includes/reporting.inc");
include_once($path_to_root . "/projects/includes/db/project_boq_item_groups_db.inc");
include_once($path_to_root . "/projects/includes/db/project_payment_application_db.inc"); 
include_once($path_to_root . "/projects/includes/db/project_payment_application_details_db.inc");   
include_once($path_to_root . "/projects/includes/db/projects_db.inc");
include_once($path_to_root . "/projects/includes/ui/project_payment_application_ui.inc");
include_once($path_to_root . "/projects/includes/db/project_boq_items_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 Payment Application"), false, false, "", $js);

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

simple_page_mode(true);

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

$boq_group_id = 0;
//if (isset($_GET['BOQGroupId']))
//{
//    $_POST['BOQGroupId'] = $_GET['BOQGroupId'];
//}
if(isset($_POST['boq_item_group_id']) && $_POST['boq_item_group_id'] > 0){
    $boq_group_id = $_POST['boq_item_group_id'];
}



function display_project_payment_application_header($payment_application_id)
{
    global $approval_statuses, $Refs;

    $dec2 = 6;

    br();    
    start_outer_table(TABLESTYLE2, "width=50%"); // outer table
    start_table(TABLESTYLE2);  
    table_section(1, "50%");
    
    if($payment_application_id > 0){
        $payment_application_header = get_project_payment_application_header($payment_application_id);
        $_POST['project_id'] = $payment_application_header['project_id']; 
        $_POST['project_description'] = $payment_application_header['project_description']; 
        $_POST['department_name'] = $payment_application_header['department_name']; 
        $_POST['customer_id'] = $payment_application_header['customer_id']; 
        $_POST['customer_name'] = $payment_application_header['customer_name']; 
        $_POST['branch_code'] = $payment_application_header['branch_code']; 
        $_POST['project_manager_name'] = $payment_application_header['project_manager_name'];
        $_POST['reference'] = $payment_application_header['reference'];
        $_POST['tran_date'] = sql2date($payment_application_header['ord_date']);
        $_POST['project_site_description'] = $payment_application_header['project_site_description'];
        
        
        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']);
        $_POST['customer_id'] = $project['customer_id']; 
        $_POST['department_name'] = $project['department_name']; 
        $_POST['customer_name'] = $project['customer_name']; 
        
        if(!isset($_POST['branch_code'])){
            $_POST['branch_code'] = -1; //$project['branch_code']; 
        }
        $_POST['project_manager_name'] = $project['project_manager_name'];
        $_POST['reference'] = $Refs->get_next(ST_PROJECT_PAYMENT_APPLICATION);
    }
    

	
//    label_row(_("Department:"), $_POST['department_name'], null, null, null);
    label_row(_('Customer:'), $_POST['customer_name'], null, null ,false);
    hidden('customer_id', $_POST['customer_id']);
    customer_branches_list_row("Branch: ", get_post('customer_id'), 'branch_code', null, false);
    
    if($payment_application_id > 0){
        if(strlen($_POST['project_site_description']) > 0){
            label_row("Job :", $_POST['project_site_description']);
        }
        else{
            label_row("Job :", "No Site selected");
        }
    }
    else{
        project_sites_list_row("Job :", "project_site_id", get_post('project_id'), null, "Select a job" , true);
    }
    
    
    
    
    table_section(2, "50%");
    ref_row("Reference:", 'reference');
    date_row("Date:", "tran_date", null);   
    label_row("Project Manager:", $_POST['project_manager_name'], null, null, 50, 150);    
    
    end_table();
    
    
    hidden('payment_application_id', $payment_application_id); 
    
    end_outer_table(1); // outer table
    

}


function display_ppa_boq_item_groups($payment_application_id)
{
    global $Ajax;
    
    $boq_groups = array();
    
    $Ajax->activate('iou_details');

    $project_id = get_post('project_id');
    
    build_pa_boq_groups_array($boq_groups, $project_id, $payment_application_id);
    
//    $result = get_project_boq_item_groups($project_id);
    div_start('iou_details');

    start_table(TABLESTYLE, "width=60%");

    $th = array(_("Group"), _("Group Total"), _("Group Taxes Total"), "");
    table_header($th);

    $k=0; //row colour counter

//    while ($myrow = db_fetch($result))
    foreach ($boq_groups as $myrow) {
            display_ppa_boq_item_group($myrow);
    }
    
    hidden('payment_application_id', $payment_application_id);
   
    end_row();   
    
    display_pa_total($boq_groups);
    
    end_table(1);
    div_end();
}

function can_process($pa_id)
{
    global $Refs;
    
    if(!(get_post('project_id') > 0)){
        display_error("Please select a project");
        set_focus('project_id');
        return false;
    }
            
    if(!(get_post('customer_id') > 0)){
        display_error("No customer selected for this Payment Application");
        set_focus('customer_id');
        return false;
    }
    
    if(!(get_post('branch_code') > 0)){
        display_error("Please select a custmer branch");
        set_focus('branch_code');
        return false;
    }
    
       
    if(!$Refs->is_valid(get_post('reference'))){
        display_error("Please enter a reference.");
        set_focus('reference');
        return false;
    }
    
    $ref_msg = reference_exists($_POST['reference'], ST_PROJECT_PAYMENT_APPLICATION, 0);
    if($ref_msg){
        $message = $ref_msg;
        $set_focus = 'reference';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);       
    }
    
//    if($pa_id == -1 && !is_new_reference(get_post('reference'), ST_PROJECT_PAYMENT_APPLICATION)){
//        display_error("Entered reference is already in use.");
//        set_focus('reference');
//        return false;
  //  }
            
    return true;
}
    
function save_pa($payment_application_id)
{       
    if(!can_process($payment_application_id)){
        return;
    }
                  
    $spa_msg = save_payment_application($payment_application_id, get_post('project_id'), get_post('customer_id'), 
                                        get_post('branch_code'), $_POST['reference'], $_POST['tran_date']); 
    return $spa_msg;   
}        
   
//--------------------------------------------------------------------------------------------------

if ($Mode == 'RESET')
{
	$selected_id = -1;
}

if (isset($_POST['_selected_id_update']) )
{
	$selected_id = $_POST['selected_id'];
	//$Ajax->activate('_page_body');
}

//if (list_updated('employee_code'))

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

if(isset($_POST['Update_project_payment_application_details'])){
    
    if(can_process($payment_application_id)){
        $uiou = save_project_payment_application(get_post('project_id'), $payment_application_id, $boq_group_id, get_post('project_site_id'));
        if($uiou["success"] !== true){
            display_error($uiou["message"]);
        }
        else{
            $payment_application_id = $uiou['trans_no'];
            display_note($uiou["message"]);
        }
    }
}

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

    $uiou = remove_project_payment_application_details($payment_application_id, $boq_group_id);
    if($uiou["success"] !== true){
        display_error($uiou["message"]);
    }
    else{
        display_note($uiou["message"]);
    }
}


if(isset($_POST['Recalculate_Poject_PA'])){
    
    if($payment_application_id > 0){
        recalculate_poject_payment_application($payment_application_id);
        display_notification("Payment Application $payment_application_id has been recalculated.");    
    }
    else{
        display_error("No Payment Application selected.");
    }
}


$button_id = find_submit("Edit");
if(isset($_POST['Edit'.$button_id])){    
    $msg_spa = save_pa($payment_application_id);
    if($msg_spa["success"] !== true){
        display_error($msg_spa["message"]);
    }
    else{
//        meta_forward($forward_to, $params);
        hidden('payment_application_id', $msg_spa["trans_no"]);
        meta_forward($_SERVER['PHP_SELF'],  "PAId=".$msg_spa["trans_no"]."&BOQGroupId=".$button_id);
       
//        display_notification($spa_msg["message"]);
    } 
}

//if(isset($_POST['Recalculate_Poject_PA'])){
//    
//    if($payment_application_id > 0){
//        recalculate_poject_payment_application($payment_application_id);
//        display_note("Payment Application $payment_application_id has been recalculated.");    
//    }
//    else{
//        display_error("No Payment Application selected.");
//    }
//}


//if(isset($_POST['update'])){      
//    
//    $boq_item_groups = get_project_boq_item_groups($_POST['project_id']);
//      
//        $k = 0;
//        $selected_group_id = 0;
//        while($selected_group_id = db_fetch($boq_item_groups)){                      
//            
//            if(isset($_POST['check_item_'.$myrow["id"]]) && ($_POST['check_item_'.$myrow["id"]].$selected_group_id['id'] ==true )) { 
//               
//                insert_project_application_payment_header_for_selected_item($_POST['project_id'], $customer_id, 
//                                                                            $_POST['reference'], $_POST['tran_date']);
//                
//        $k++;
//        end_row();
//       }   
//    }
//    
//}
//  
////}     
//-------------------------------------------------------------------------------------------------        

	$Ajax->activate('_page_body');
//--------------------------------------------------------------------------------------------------  

if (!@$_GET['popup']){
	start_form();
}

display_project_payment_application_header($payment_application_id);

//br();

hidden('payment_application_id', $payment_application_id);

//display_ppa_boq_item_groups($payment_application_id);

submit_center_first('Recalculate_Poject_PA', _("Recalculate Payment Application Summaries"), '', 'default');

if($payment_application_id > 0){
    echo(get_project_trans_view_str(ST_PROJECT_PAY_APP_BOQ_GROUPS, $payment_application_id, "View Payment Application"));
}

//submit_center_first('Recalculate_Poject_PA', _("Recalculate Payment Application Summaries"), '', 'default');

br(2);

start_table(TABLESTYLE2, "width=30%");  
project_boq_item_groups_list_row("BOQ Item Group", "boq_item_group_id", $_POST['project_id'], null, "Select a BOQ Item Group", true);
end_table();

display_project_payment_application_details(get_post('project_id'),$payment_application_id, $boq_group_id, 
                                            get_post('project_site_id'), date2sql(get_post('tran_date')));

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


?>
