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

$page_security = 'SA_I_OWE_YOU_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/data_checks.inc");
include_once($path_to_root . "/petty_cash/includes/db/i_owe_you_db.inc");
include_once($path_to_root . "/petty_cash/includes/db/i_owe_you_advances_db.inc");
include_once($path_to_root . "/petty_cash/includes/db/petty_cash_floats_db.inc");
include_once($path_to_root . "/includes/db/group_companies_db.inc");

include_once($path_to_root . "/petty_cash/includes/db/project_floats_db.inc");
include_once($path_to_root . "/petty_cash/includes/db/petty_cash_payments_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();
}

simple_page_mode(true);

page(_($help_context = "I Owe You Advances"), false, false, "", $js);

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


if (isset($_GET['Processed_ID'])) 
{
	//return;
        
    $trans_no = $_GET['Processed_ID'];
	$trans_type = ST_I_OWE_YOU_ADVANCES_BATCH;
    $message = "I Owe You advances batch $trans_no has been processed.";
    
	display_notification_centered($message);
        
//	display_note(print_document_link($trans_no, _("&Print this I Owe You  batch"), true, $trans_type), 0, 0);

	hyperlink_no_params("$path_to_root/petty_cash/i_owe_you_advances.php", _("Create another &I Owe You advances batch"));

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

	display_footer_exit();
}



function display_ious_for_advances()
{
    display_heading("I Owe Yous for Advances");
    
    start_table(TABLESTYLE, "width=95%");

    $th = array(_("Id"),"Project", _("Employee Name"), "Float", _("Type"),
                _("Date"),_("Amount"), "Payments (All)", "Advances", "Comment", "Advance Amount", "Select");
    table_header($th);

    $j = 1;
    $k=0; //row colour counter


    $approval_statuses_in = AS_NEW;

    $ious = array();

    $total =0;
    $result = get_i_owe_yous_for_advances_entry($_POST['from_date'], $_POST['to_date'], $_POST['float_id']);
    while ($iou_line = db_fetch($result))
    {
        alt_table_row_color($k);

      
        label_cell(get_petty_cash_trans_view_str(ST_I_OWE_YOU, $iou_line["id"]), "align=center");        
        label_cells('',$iou_line["project_description"]);
        label_cells('', $iou_line["employee_code"]);
//      label_cells('',get_group_company_employee_formatted_long_name($iou_line["company_code"], $iou_line["employee_code"]));
        label_cells('',$iou_line["float_name"]);
        label_cells('',$iou_line["type_name"]);
        label_cells('',sql2date($iou_line["tran_date"]));
        qty_cell($iou_line["amount"], false, 2);
        
        $advace = $iou_line['advance_amount'];
        $bank_payments = $iou_line['bank_payments'];
        $pay_tot = get_i_owe_you_payments_total($iou_line['id'], -1);
        $total_payments = $pay_tot + $advace + $bank_payments;
        qty_cell($total_payments, false, 2);
        
        $advance_amount_link = get_petty_cash_trans_view_str(ST_I_OWE_YOU_ADVANCES, $iou_line["id"], number_format($iou_line["advance_amount"], 2));
        label_cell($advance_amount_link, "align=right");   

        label_cells('', $iou_line["comments"]);

        amount_cells(null, $iou_line['id']."_".'advance_amount', $iou_line["planned_amount"]);  

        check_cells('', $iou_line["id"]."_".'selected_'.$iou_line["id"]);       
        
        end_row();
        
//        if(isset($_POST['calculate_total'])){
            if(isset($_POST[$iou_line['id']."_".'advance_amount']) && isset($_POST[$iou_line["id"]."_".'selected_'.$iou_line["id"]])){
                $total += input_num($iou_line['id']."_".'advance_amount');
            }
//        }          
    }    
        
    start_row();    
        label_cell("Total:", "colspan=10 align=right");
        amount_decimal_cell($total);
        label_cell("");
    end_row();

    end_table(1);   
}

function can_process()
{     
    $user_id = $_SESSION['wa_current_user']->user;
    $cpfa = check_petty_cash_float_access($_POST['float_id'], $user_id);
    if ($cpfa['success'] !== true)
    {
        display_error($cpfa['message']);
        set_focus('');
        return false;  
    }
    
    $result = get_i_owe_yous_for_advances_entry($_POST['from_date'], $_POST['to_date'], $_POST['float_id']);
    
    $selection_count = 0;
    $total_advances = 0;
    while($iou_line = db_fetch($result)){  
        if((isset($_POST[$iou_line["id"]."_".'selected_'.$iou_line["id"]])) && ($_POST[$iou_line["id"]."_".'selected_'.$iou_line["id"]] == true))
        {           
            if(!check_num($iou_line['id']."_".'advance_amount', 0.0001)){
                display_error("Advance amount entered for IOU ".$iou_line['id']." should be numeric and possitive.");
                set_focus($iou_line['id']."_".'advance_amount');
                return false;
            }

            $selection_count++;
            $total_advances += input_num($iou_line['id']."_".'advance_amount');
            
            $project_id = $iou_line['project_id'];
            $project_float = get_project_float_by_project_id($project_id);
            if($project_float && $project_float['inactive'] == 0){
                if($iou_line['company_code'] == $project_float['company_code'] && $iou_line['employee_code'] == $project_float['employee_code']){                    
                    $payment_amount = input_num($iou_line['id']."_".'advance_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;
                        display_error($message);
                        return false;
                    }
                }
            }
        }
    }  

    if(!($selection_count > 0)){
        display_error("No records selected.");
        set_focus('');
        return false;
    }
    
    if(!($total_advances > 0)){
        display_error("Total of all advances should be a possitive value.");
        set_focus('');
        return false;
    }
    
    if(!is_date($_POST['batch_date'])){
        display_error("Batch date is not a valid date.");
        set_focus('batch_date');
        return false;
    }
    
    if (!is_date_in_fiscalyear($_POST['batch_date'])) {
        display_error(_("The entered date is not in fiscal year.")); 
        set_focus('batch_date');
        return false;        
    }
        
    $msg = is_accounting_period_open($_POST['batch_date']);
    if ($msg['success'] !== true){
        display_error($msg['message']); 
        set_focus('batch_date');
        return false;        
    }
        
    return true;    
} 

function add_to_float_advances_array(&$float_advances, $float_id, $advance_amount)
{
    if(is_array($float_advances)){
        foreach ($float_advances as &$float_advance) {
            if(isset($float_advance['float_id']) && $float_advance['float_id'] == $float_id){
                $float_advance['total_advances'] += $advance_amount;
                return;
            }        
        }
    }
    
    $new_float_advance_line = array('float_id' => $float_id, 
                                'total_advances' => $advance_amount);
    $float_advances[] = $new_float_advance_line;
}

function create_i_owe_you_advances_batch()
{
        $max_value = get_iou_advances_max_batch_no();
        $max_batch_no = $max_value['max_batch_no'];
        $max_batch_no++;
        
        if(!($max_batch_no > 0)){
            return  array("success" => false, "message" => "Next batch number not possitive. You may try saving again.");
        }
    
        $result = get_i_owe_yous_for_advances_entry($_POST['from_date'], $_POST['to_date'], $_POST['float_id']);
    
        $updates_count = 0;
        $total_advances = 0;
        $total_advances_paid = 0;
        $float_advances = array();
        
        while($iou_line = db_fetch($result)){  
            if((isset($_POST[$iou_line["id"]."_".'selected_'.$iou_line["id"]])) && ($_POST[$iou_line["id"]."_".'selected_'.$iou_line["id"]] == true))
            {           
                $advance_amount = input_num($iou_line['id']."_".'advance_amount');  
                
//                $total_advances_paid = get_i_owe_you_total_advances_paid($iou_line['id']);
//                $total_advances_paid = get_i_owe_you_advances_paid_total($iou_line['id']);
//                $total_payments = get_i_owe_you_payments_total($iou_line['id'], -1);
//                $total = $total_advances_paid + $total_payments + $advance_amount;
//                
//                if(($total) > $iou_line['amount']){
//                    $message = "With this advance payment, advances plus the payments total of "
//                                .$total." will be more than the IOU amount of ".$iou_line['amount']
//                                ." for the IOU ".$iou_line['id'];
//                    return array("success" => false, "message" => $message);
//                }
                
                $cc_msg = can_commit_iou_advance($iou_line['id'], $iou_line['amount'], $advance_amount, $total_advances_paid);
                if($cc_msg['success'] !== true ){
                    return $cc_msg;
                } 
                
                
                add_to_i_owe_you_advances_details($max_batch_no, $iou_line['id'], $advance_amount, $iou_line['float_id']);
                
                $n = update_i_owe_you_advances($iou_line['id'], $max_batch_no, $total_advances_paid + $advance_amount); 

                if(!($n == 1 )){
                    return array("success" => false, "message" => "IOU ".$iou_line['id']." has been updated by amother user.");
                }  

                $total_advances += input_num($iou_line['id']."_".'advance_amount');

                $updates_count++;
                
                add_to_float_advances_array($float_advances, $iou_line['float_id'], $advance_amount);
                
                $project_float = get_project_float_by_project_id($iou_line['project_id']);
                if($project_float && $project_float['inactive'] == 0){
                    if($iou_line['company_code'] == $project_float['company_code'] && $iou_line['employee_code'] == $project_float['employee_code']){
                        add_to_project_float(ST_I_OWE_YOU_ADVANCES_BATCH, $iou_line['id'], $iou_line['project_id'], $project_float['company_code'], 
                                                $project_float['employee_code'], $advance_amount, $iou_line['tran_date']);
                    }
                }
            }
        }
        
        if(!($updates_count > 0)){
            return  array("success" => false, "message" => "No records updated.");
        }
        if(!($total_advances > 0)){
            return  array("success" => false, "message" => "Total of advances is not possitive.");
        }

        $float_updates = 0;
        foreach ($float_advances as $float_advance) {
            if(isset($float_advance['float_id']) && $float_advance['float_id'] > 0 && $float_advance['total_advances'] > 0){
                add_to_petty_cash_float(ST_I_OWE_YOU_ADVANCES_BATCH, $max_batch_no, $float_advance['float_id'], -$float_advance['total_advances'], Today());      
                $float_updates ++;
                
            }
        }
        
        if(!($float_updates > 0)){
            return  array("success" => false, "message" => "No float balance updated.");
        }
        
        $n = add_i_owe_you_advances_header($max_batch_no, $total_advances, $_POST['batch_date']);
        if($n != 1){
            return  array("success" => false, "message" => "Could not create IOU advances batch.");
        }
        
        delete_planned_i_owe_you_advances();
        
        return  array("success" => true, "trans_no" => $max_batch_no, "message" => "IOU advances batch No $max_batch_no created.");
         
} 

function can_commit_iou_advance($iou_id, $iou_amount, $advance_amount, &$total_advances_paid)
{
    $iou = get_i_owe_you_record($iou_id);
    $total_advances_paid = $iou['advance_amount'];
    $bank_payments = $iou['bank_payments'];

    $total_payments = get_i_owe_you_payments_total($iou_id, -1, 1);
    $total = $total_advances_paid + $total_payments + $bank_payments + $advance_amount;

    if(($total) > $iou_amount){
        $message = "IOU ".$iou_id." - with this advance payment ".number_format($advance_amount,2)
                                        .", total of all the payments ".number_format($total,2)
                                        ." (=advances ".number_format($total_advances_paid,2)
                                        ." + IOU Payments ".number_format($total_payments,2)
                                        ." + bank payments ".number_format($bank_payments,2)                                        
                                        ." + ".number_format($advance_amount,2)                                        
                                        .") will be more than the IOU amount of ".number_format($iou_amount,2);
        return array("success" => false, "message" => $message);
    }
    
    return array("success" => true, "message" => '');
}


function save_planned_iou_advances()
{
        delete_planned_i_owe_you_advances();
        
        $result = get_i_owe_yous_for_advances_entry($_POST['from_date'], $_POST['to_date'], $_POST['float_id']);
    
        $updates_count = 0;
        $total_advances = 0;
        $total_advances_paid = 0;
        
        while($iou_line = db_fetch($result)){  
            if((isset($_POST[$iou_line["id"]."_".'selected_'.$iou_line["id"]])) && ($_POST[$iou_line["id"]."_".'selected_'.$iou_line["id"]] == true))
            {           
                $advance_amount = input_num($iou_line['id']."_".'advance_amount');  
                $cc_msg = can_commit_iou_advance($iou_line['id'], $iou_line['amount'], $advance_amount, $total_advances_paid);
                if($cc_msg['success'] !== true ){
                    return $cc_msg;
                } 
                
                add_planned_i_owe_you_advance($iou_line['id'], $advance_amount);
            }
        }

        return  array("success" => true, "message" => "Selected I Owe You advances have been saved.");
        


}

if(isset($_POST['Process_IOU_Advances'])){    
 
    if(can_process()){    
        begin_transaction();
        $cab = create_i_owe_you_advances_batch(); 
        if($cab['success'] !== true ){
            cancel_transaction();
            display_error($cab['message']);        
        } else{
            commit_transaction();
            $batch_no = $cab['trans_no'];
            meta_forward($_SERVER['PHP_SELF'], "Processed_ID=$batch_no");
//            display_notification($cab['message']);
        }
    }
    
}
   
if(isset($_POST['Save_IOU_Advances'])){    
 
    if(can_process()){    
        begin_transaction();
        $cab = save_planned_iou_advances(); 
        if($cab['success'] !== true ){
            cancel_transaction();
            display_error($cab['message']);        
        }
        else{
            commit_transaction();
            display_notification($cab['message']);
        }
    }
}



start_form();

br();

$Ajax->activate('leaves');

div_start('leaves');

start_table();
date_cells("From Date:", 'from_date', '', null, -7);
date_cells("To Date:", 'to_date');
petty_cash_floats_list_cells("Floats:", 'float_id', null, 'Select a Float', true);

submit_cells('SearchOrders', _("Search"),'',_('Select documents'), 'default');

end_table();
br();

display_ious_for_advances();

br();

//display_new_ious();

div_end();
//submit_center('UpdateData', _("Update"), true, false, 'default');
//submit_center('calculate_total', _("Calculate"), true, false, 'default');

submit_center_first('Save_IOU_Advances', _("Save"), '', 'default');
submit('Calculate_IOU_Advances', 'Calculate', true, '', 'default');

br(2);
start_table();
date_cells("Batch Date:", 'batch_date');
end_table();
br();
submit_center_first('Process_IOU_Advances', _("Process IOU Advances Batch"), '', 'default');


br(2);

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



?>
