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

$page_security = 'SA_PROJECT_FLOAT_ADVANCES';
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 . "/petty_cash/includes/db/project_advance_batches_db.inc");
include_once($path_to_root . "/petty_cash/includes/db/project_floats_db.inc");
include_once($path_to_root . "/petty_cash/includes/db/i_owe_you_db.inc");
include_once($path_to_root . "/projects/includes/db/projects_db.inc");
//include_once($path_to_root . "/includes/project_cost_functions.inc");
//include_once($path_to_root . "/includes/db/approval_functions_db.inc");
//include_once($path_to_root . "/projects/includes/db/projects_db.inc");
//include_once($path_to_root . "/gl/includes/db/utility_expense_types_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 Advance Batches"), false, false, "", $js);

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


$ub_no = -1;
 
if (isset($_GET['UBNo']))
{
    $_POST['UBNo'] = $_GET['UBNo'];
    set_session_variable("ST_UTILITY_BILLS_ub_no", $_POST['UBNo']);
}


if (isset($_GET['NewOrder']))
{
    $_POST['UBNo'] = -1;
    set_session_variable("ST_UTILITY_BILLS_ub_no", $_POST['UBNo']);

} 

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

if (isset($_GET['Added_ID'])) 
{
	//return;
        
    $trans_no = $_GET['Added_ID'];
	$trans_type = ST_PROJECT_ADVANCE_BATCH;

    
	display_notification_centered("Project Advances batch $trans_no has been processed.");
        
	display_note(print_document_link($trans_no, _("&Print this Project Advance batch "), true, $trans_type), 0, 0);

	hyperlink_no_params("$path_to_root/petty_cash/inquiry/project_advance_batches_inquiry.php", _("Process another &Project Advances batch"));

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

	display_footer_exit();
}


//function can_delete_project_advance_batch_item($ub_no)
//{
//    $line_count = get_project_advance_batch_line_count($ub_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_commit_pab_header($ub_no)
{

//    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 (strlen($_POST['reference']) == 0)
    {
        $message = "Reference is mandatory.";
        $set_focus = 'reference';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }

    $rm = reference_exists($_POST['reference'], ST_PROJECT_ADVANCE_BATCH, $ub_no);
    if($rm) 
    {
        $message = $rm;
        $set_focus = ('reference');
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    if(!is_date($_POST['tran_date']))
    {
        $message = "Date entered is not a valid date.";
        $set_focus = 'tran_date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }
    
    if($_POST['float_id'] == -1)
    {
        $message = "Please select a Float.";
        $set_focus = 'float_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);    
    }
          
    $pabh = get_project_advance_batch_header($ub_no);
    if($pabh['paid'] == true)
    {
        $message = "This Project Advances batch has been processed already.";
        $set_focus = '';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);    
    }
    
    return array("success" => true, "message" => "");    
}

 
function can_commit_pab_line($ub_no)
{    
    if(!($_POST['line_project_id'] > 0))
    {
        $message = "Please select a project.";
        $set_focus = 'line_project_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    if(!(input_num('amount') > 0))
    {
        $message = "Amount should be greater than zero.";
        $set_focus = 'amount';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    if(!is_date($_POST['period_from']))
    {
        $message = "Period from date is not a valid date.";
        $set_focus = 'period_from';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);         
    }
    
    if(!is_date($_POST['period_to']))
    {
        $message = "Period to date is not a valid date.";
        $set_focus = 'period_to';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);         
    }
    
    if(date1_greater_date2($_POST['period_from'], $_POST['period_to']))
    {
        $message = "Period from date cannot be greater than period to date.";
        $set_focus = 'period_to';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
    }
            
    $project_float = get_project_float_by_project_id($_POST['line_project_id']);
    if(!($project_float && $project_float['inactive'] == 0)){
        $message = "No active project float found for the selected project.";
        $set_focus = 'line_project_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
    }
    
    $project_id = $_POST['line_project_id'];
//            $project_float = get_project_float_by_project_id($project_id);
    if($project_float && $project_float['inactive'] == 0){                   
        $payment_amount = input_num('amount');
        $pf_balance = get_project_float_balance($project_id);
        $pf_new_balance = $pf_balance + $payment_amount;
        $pf_limit = $project_float['amount'];
        if($pf_new_balance > $pf_limit){
            $project = get_project_record($project_id);
            $message = "This advance will make the Float balance of Project ".$project['description']." "
                        .number_format($pf_new_balance,2).", higher than its limit of ".$pf_limit;
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
        }
        
    }
    
    return array("success" => true, "message" => "");    
}

   

function save_project_advance_batch_header(&$ub_no)
{     
    $ub_no = write_project_advance_batch_header($ub_no, $_POST['reference'],  
                                                0, $_POST['tran_date'], 
                                                $_POST['float_id'], $_POST['comment'] );   
        
    
    if($ub_no > 0){
        set_session_variable("ST_UTILITY_BILLS_ub_no", $ub_no);
        return array("success" => true, 'trans_no' => $ub_no, "message" => "Utility bills header information have been saved.");
    }
    else{
        return array("success" => false, 'trans_no' => '', "message" => "Could not save Utility bills header.");
    }
}



function save_project_advance_batch_detail(&$ub_no, $selected_id)
{
    write_project_advance_batch_detail($ub_no, $selected_id, $_POST['line_project_id'], 
                                $_POST['description'], input_num('amount'),
                                $_POST['period_from'], $_POST['period_to'] ); 
    return array("success" => true, 'trans_no' => '', "message" => "");
}


function save_project_advance_batch(&$ub_no, $selected_id)
{
    $temp_ub_no = $ub_no;
    
    $h_msg = can_commit_pab_header($ub_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_commit_pab_line($ub_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 = save_project_advance_batch_header($ub_no);
    if($msg["success"] !== true){
        cancel_transaction();
        return array("success" => false, 'trans_no' => $ub_no, "message" => $msg["message"]);
    }

    $msg = save_project_advance_batch_detail($ub_no, $selected_id);
    $ub_lines_total = get_ub_lines_total($ub_no);
     
    update_header_total($ub_lines_total, $ub_no);
     
    if($msg["success"] !== true){
        cancel_transaction();
        return array("success" => false, 'trans_no' => $ub_no, "message" => $msg["message"]);
    }
    
//    commit_transaction();
    if($temp_ub_no > 0){
        return array("success" => true, 'trans_no' => $ub_no, "message" => $msg["message"]);
    }
    else{
        return array("success" => true, 'trans_no' => $ub_no, "message" => "Utility Bill $ub_no has been created.");
    }

}

function display_project_advance_batch_header($ub_no)
{
    global $approval_statuses, $Refs;
    
    if($ub_no > 0){
        $ub_header = get_project_advance_batch_header($ub_no);
        
        $project_id = $ub_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'] = $ub_header['project_id'];
    
        if(!isset($_POST['reference'])){
            $_POST['reference'] = $ub_header['reference'];
        }

        if(!isset($_POST['tran_date'])){
            $_POST['tran_date'] = sql2date($ub_header['tran_date']);
        }
        
        if(!isset($_POST['float_id'])){
            $_POST['float_id'] = $ub_header['float_id'];
        }

        if(!isset($_POST['comment'])){
            $_POST['comment'] = $ub_header['comment'];
        }             
    
    }
    else{
        $_POST['approval_status'] = 0;
    }
        
    start_outer_table(TABLESTYLE2, "width=20%"); // outer table
    start_table(TABLESTYLE2);  
        table_section(1, "35%");
        
        if($ub_no>0){
            ref_row("Reference:", 'reference', null, null, null);  
        }
        else{
            ref_row(_("Reference:"), 'reference', '', $Refs->get_next(ST_PROJECT_ADVANCE_BATCH));
        }
        
        date_row("Date", 'tran_date');
        petty_cash_floats_list_row("Float:", 'float_id', null, 'Please select a Float');
        textarea_row("Comment:", 'comment', null, 30, 2);

     
    end_table(1);

    end_outer_table(1); // outer table
    hidden('UBNo', $ub_no);
 
}


function display_project_advance_batch_details($ub_no)
{  
    //global $project_invoice_line_types;    
          
    $result = get_project_advance_batch_details($ub_no);  
    
                              
    start_table(TABLESTYLE, "width=70%");
    $th = array( _('Project'), _('Description'),
                 _('Period From'), _('Period To'),  _('Amount'), "", "");              

    table_header($th);
    $k = $total_ub = 0; //row colour counter
  
      
    while ($myrow = db_fetch($result))
    {
        alt_table_row_color($k);

        label_cell($myrow["project_description"]);
        label_cell($myrow["description"]);
        label_cell(sql2date($myrow["period_from"]), "align=center");
        label_cell(sql2date($myrow["period_to"]), "align=center");
     
        label_cell(number_format($myrow["amount"], 2), "align=right");
       // $_POST['amount_total'] += $myrow["amount"];
     
        edit_button_cell("Edit".$myrow["id"], _("Edit"));    
        delete_button_cell("Delete".$myrow["id"], _("Delete"));  
        
        end_row();        
      
        $total_ub += $myrow["amount"];
    }
    start_row();
    label_cell("Total", "align=right colspan=3");
    label_cell("<b>".number_format($total_ub, 2)."</b>", "align=right");
    end_row();
    
    end_table();
      
}

function display_project_advance_batch_edit_controls($selected_id, &$Mode)
{
    if ($Mode =='Edit')   
    {
        $myrow = get_project_advance_batch_line($selected_id); 
    
        $_POST['line_project_id'] = $myrow["project_id"];
        $_POST['description'] = $myrow["description"];
        $_POST['amount'] = $myrow["amount"];    
        $_POST['period_from'] = sql2date($myrow["period_from"]);  
        $_POST['period_to'] = sql2date($myrow["period_to"]); 
       
    }
    else{
   
    }

    hidden('selected_id', $selected_id );
    br();

    div_start('billing_items');
    start_table(TABLESTYLE2);
  
    project_list_row("Project:", 'line_project_id', null, "Please selecta project");
    text_row("Description:", 'description', null, 30, 200);
    amount_row("Amount:", 'amount');
    date_row("Period From:", 'period_from');
    date_row("Period To:", 'period_to');

    end_table(1);
    div_end();

}

function process_project_advance_batch($ub_no)
{
    $pabh = get_project_advance_batch_header($ub_no);
    $result = get_project_advance_batch_details($ub_no);  
    
    while ($myrow = db_fetch($result))
    {
        $project_id = $myrow['line_project_id'];  
        $project_float = get_project_float_by_project_id($project_id);
        if(!($project_float && $project_float['inactive'] == 0)){
            $project = get_project_record($myrow['project_id']);
            $message = "No active Project Float found for the project ".$project['description'];
            return array("success" => false, "trans_no" => $ub_no, "message" => $message);
        }
    
                       
        $payment_amount = $myrow('amount');
        $pf_balance = get_project_float_balance($project_id);
        $pf_new_balance = $pf_balance + $payment_amount;
        $pf_limit = $project_float['amount'];
        if($pf_new_balance > $pf_limit){
            $project = get_project_record($project_id);
            $message = "This advance will make the Float balance of Project ".$project['description']." "
                        .number_format($pf_new_balance,2).", higher than its limit of ".$pf_limit;
            return array("success" => false, "trans_no" => $ub_no, "message" => $message); 
        
        }
        
        add_to_project_float(ST_PROJECT_ADVANCE_BATCH, $ub_no, $project_float['project_id'], $project_float['company_code'], 
                                        $project_float['employee_code'], $myrow['amount'], date2sql(Today()));
        
        add_to_petty_cash_float(ST_PROJECT_ADVANCE_BATCH, $ub_no, $pabh['float_id'], -$myrow['amount'], Today());
        
        $n = update_project_advance_batch_detail_paid($myrow['id']);
        if($n != 1){
            return array("success" => false, "trans_no" => $ub_no, "message" => "Another user has updated Project Advances Batch detail ".$myrow['description']);
        }
    }
    
    $k = update_project_advance_batch_header_paid($ub_no);
    if($k != 1){
            $message = "Another user has updated the Project Advances Batch ".$ub_no;
            return array("success" => false, "trans_no" => $ub_no, "message" => $message);
    }
    else{
        return array("success" => true, "trans_no" => $ub_no, "message" => '');
    }
    
}
 
if(isset($_POST['Process_Utility_Bill_Header'])){
        
    $h_msg = can_commit_pab_header($ub_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 = process_project_advance_batch($ub_no);
    
        if($msg['success'] !== true){
            cancel_transaction();
            display_error($msg['message']);
        }
        else{
            commit_transaction();
            meta_forward($_SERVER['PHP_SELF'], "Added_ID=$ub_no");
        }

    }

}

 
if(isset($_POST['Save_Utility_Bill_Header'])){
        
    $h_msg = can_commit_pab_header($ub_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_project_advance_batch_header($ub_no);
    
        if($msg['success'] !== true){
            cancel_transaction();
            display_error($msg['message']);
        }

    }

}


if(isset($_POST['Add_Utility_bills_Item']) || isset($_POST['Utility_bills_Item'])){
        
    $msg = save_project_advance_batch($ub_no,$selected_id);
    
    if($msg['success'] !== true){
        display_error($msg['message']);
    }
    else{
        $_POST['UBNo'] = $msg['trans_no'];
        display_notification($msg['message']);
//        display_notification("Taxes have been recalculated and updated.");
        $Mode = 'RESET';
    }

}


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



if ($Mode == 'Delete')
{
    //if(can_delete_project_advance_batch_item($ub_no)){
       // begin_transaction();
        $recs = delete_project_advance_batch_item($selected_id);
         
        $ub_lines_total = get_ub_lines_total($ub_no);
     
        update_header_total($ub_lines_total, $ub_no);

}

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

display_project_advance_batch_header($ub_no);   

if($ub_no > 0){
    submit_center_first('Save_Utility_Bill_Header', _("Save"), '', 'default');
    submit_center_last('Process_Utility_Bill_Header', _("Process"), '', 'default');
    br(2);

}

//------------------------------------------------------------------------------------------------------------
         
display_project_advance_batch_details($ub_no);

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

display_project_advance_batch_edit_controls($selected_id, $Mode);


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


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




?>
