<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_I_OWE_YOU_EXPENSES_ENTRY';
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_expenses_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 . "/includes/ui/ui_lists_group_companies.inc");
include_once($path_to_root . "/includes/db/group_companies_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 = "Select I Owe Yous for Expenses Entry"), false, false, "", $js);




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


function save_iou_expences_batch($batch_no, $project_id, $float_id, $tran_date)
{
    $batch_total = $batch_advances_total = 0;
    
    $totals = get_i_owe_you_batch_totals($batch_no);
    if(isset($totals['iou_batch_total']) && $totals['iou_batch_total'] > 0){
        $batch_total = $totals['iou_batch_total'];
    }
    if(isset($totals['iou_batch_advances_total']) && $totals['iou_batch_advances_total'] > 0){
        $batch_advances_total = $totals['iou_batch_advances_total'];
    }
    
    
    
    $batch = get_i_owe_you_batch_header($batch_no);
    if(isset($batch['batch_no']) && $batch['batch_no'] > 0){
        $expense_batch_approved_total = get_i_owe_you_batch_expenses_approved_total($batch_no);
        update_i_owe_you_batch_header($batch_no, $expense_batch_approved_total, $batch_advances_total);
    }
    else{
        $tran_date = date2sql(Today());
        add_i_owe_you_batch_header($batch_no, $project_id, $float_id, 0, $batch_advances_total, $tran_date);
    }
}


function mark_selected_i_owe_yous($path_to_root, $iou_id, $batch_no, $from_date, $to_date, $employee_code, $type_id, $project_id, $float_id)
{    
    $any_selected = false;
    $ious = array();
    
    build_all_ious_array($ious, $iou_id, $batch_no, $from_date, $to_date, $employee_code, $type_id, $project_id, $float_id);

    $updates_count = 0;
    $batch_no = 0;
    $task_id = 0;
    $float_id = 0;
        
    begin_transaction();
    
    foreach ($ious as $iou_line) {
        
        if((isset($_POST["selected_".$iou_line["id"]])) &&
                ($_POST["selected_".$iou_line["id"]] == true))
        {
            $any_selected = true;
            $error_prefix = "I Owe You ". $iou_line["id"];
            
            // IOUs with batach numbers come first in the select sql. So $iou_line["batch_no"] == 0 means all of the IOUs with batch number are not selected.  
            if($batch_no == 0 && $iou_line["batch_no"] == 0){
                $batch_no = get_iou_next_batch_no();
                $project_id = $iou_line["project_id"];
            }
            
            if($batch_no == 0 && $iou_line["batch_no"] > 0){
                $batch_no = $iou_line["batch_no"];
                $project_id = $iou_line["project_id"];
            }
            
            if($float_id == 0){
                $float_id = $iou_line["float_id"];
            }
            
            if(!(strlen($employee_code) > 2)){
                $employee_code = $iou_line["employee_code"];
            }
            
            if($project_id != $iou_line["project_id"]){
                cancel_transaction();
                display_error($error_prefix." - Only IOUs of same project can be selected together.");
                $updates_count = -1;
                return;
            }
            
            if($employee_code != $iou_line["employee_code"]){
                cancel_transaction();
                display_error($error_prefix." - Only IOUs belongs to the same employee can be selected together.");
                $updates_count = -1;
                return;
            }
                
            if($batch_no > 0){
                if($iou_line["batch_no"] > 0 && $batch_no != $iou_line["batch_no"]){
                    cancel_transaction();
                    display_error($error_prefix." - Only IOUs of the same batch and fresh IOUs can be selected together.");
                    $updates_count = -1;
                    return;
                }
            }

//            $user_id = $_SESSION['wa_current_user']->user;
//            $cpfa = check_petty_cash_float_access($iou_line['float_id'], $user_id);
//            if ($cpfa['success'] !== true)
//            {
//                cancel_transaction();
//                display_error($error_prefix." - ".$cpfa['message']);
//                $updates_count = -1;
//                return;
//            }
            
            if($float_id != $iou_line["float_id"]){
                cancel_transaction();
                display_error($error_prefix." - Only IOUs of same float can be selected together.");
                $updates_count = -1;
                return;
            }
            
            if($batch_no > 0){
                if($iou_line["batch_no"] > 0 && $batch_no != $iou_line["batch_no"]){
                    cancel_transaction();
                    display_error($error_prefix." - This IOU is already in the batch ".$iou_line["batch_no"]." Can not add it to new batch ".$batch_no);
                    $updates_count = -1;
                    return;                    
                }
                
                if($iou_line["batch_no"] > 0 && $batch_no == $iou_line["batch_no"]){
                    $n = 1; // No need to update. It is the same batch
                }
                else{
                    $n = add_selected_iou_to_batch($iou_line["id"], $iou_line["batch_no"], $batch_no);
                }
                
                if($n !== 1){
                    cancel_transaction();
                    display_error($error_prefix." - Could not add IOU ".$iou_line["id"]." to new batch ".$batch_no);
                    $updates_count = -1;
                    return;
                }
                $updates_count++;
            }      
            
            $float_id = $iou_line["float_id"];
            
        }
    }
    
    if($batch_no > 0){
        $batch = get_i_owe_you_batch_header($batch_no);
        if(isset($batch['batch_no']) && $batch['batch_no'] > 0){
            if(!(in_array($batch['approval_status'], array(AS_NEW, AS_AWAITING_APPROVAL, AS_WITH_THE_APPROVER, AS_BACK_TO_ORIGINATOR)))){
                cancel_transaction();
                display_error("IOU Batch $batch_no is already approved or awaiting for approval. No further expences can be entered for this batch.");
                return;
            }
            $tran_date_sql = $batch['tran_date'];
        }else{            
            $tran_date_sql = date2sql(Today()); // new batch. Set to current date
        }
        
        if (!is_date_in_fiscalyear($tran_date_sql, true)) {
            display_error(_("The entered date is not in fiscal year.")); 
            return false;        
        }
        
        $msg = is_accounting_period_open($tran_date_sql, true);
        if ($msg['success'] !== true)
        {
            display_error($msg['message']); 
            return false;        
        }
         
        
        save_iou_expences_batch($batch_no, $project_id, $float_id, $tran_date_sql);
    }
    else{
        cancel_transaction();
        display_error(_("Selected Batch not available or generated next Batch No is zero. Can not enter expenses."));
        return;
    }
    
    if($updates_count > 0 && $batch_no > 0){
        commit_transaction();
        meta_forward($path_to_root . "/petty_cash/i_owe_you_expenses_entry2.php",  "IouBatchNo=$batch_no");
    }
    elseif($updates_count == 0){
        cancel_transaction();
        display_error(_("No records selected."));
    }
    else{//$updates_count = -1
        cancel_transaction();
        display_error(_("Could not update the batch."));
    }
    
}

function build_ious_with_expenses_array(&$ious, $iou_id, $batch_no, $from_date, $to_date, $employee_code, $type_id, $project_id, $float_id)
{
    $result = get_i_owe_yous_for_expenses_entry(false, $iou_id, $batch_no, $from_date, $to_date, $employee_code, $type_id, $project_id, $float_id);
    while ($myrow = db_fetch($result))
    {
        $a = array(
                "id" => $myrow["id"],
                "project_id" => $myrow["project_id"],
                "project_description" => $myrow["project_description"],
                "float_id" => $myrow["float_id"],
                "float_name" => $myrow["float_name"],
                "employee_code" => $myrow["employee_code"],
                "company_code" => $myrow["company_code"],
                "type_name" => $myrow["type_name"],
                "tran_date" => $myrow["tran_date"],
                "amount" => $myrow["amount"],
                "comments" => $myrow["comments"],
                "batch_no" => $myrow["batch_no"],
                "batch_approval_status"  => $myrow["batch_approval_status"]);

        $ious[] = $a;
    }
}

function build_new_ious_array(&$ious, $iou_id, $batch_no, $from_date, $to_date, $employee_code, $type_id, $project_id, $float_id)
{
    $result = get_i_owe_yous_for_expenses_entry(true, $iou_id, $batch_no, $from_date, $to_date, $employee_code, $type_id, $project_id, $float_id);
    while ($myrow = db_fetch($result))
    {
        $a = array(
                "id" => $myrow["id"],
                "project_id" => $myrow["project_id"],
                "project_description" => $myrow["project_description"],
                "float_id" => $myrow["float_id"],
                "float_name" => $myrow["float_name"],
                "employee_code" => $myrow["employee_code"],
                "company_code" => $myrow["company_code"],
                "type_name" => $myrow["type_name"],
                "tran_date" => $myrow["tran_date"],
                "amount" => $myrow["amount"],
                "comments" => $myrow["comments"],
                "batch_no" => $myrow["batch_no"],
                "batch_approval_status"  => $myrow["batch_approval_status"]);

        $ious[] = $a;
    }

}


function build_all_ious_array(&$ious, $iou_id, $batch_no, $from_date, $to_date, $employee_code, $type_id, $project_id, $float_id)
{
    $result = get_i_owe_yous_for_expenses_entry(false, $iou_id, $batch_no, $from_date, $to_date, $employee_code, $type_id, $project_id, $float_id);
    while ($myrow = db_fetch($result))
    {
        $a = array(
                "id" => $myrow["id"],
                "project_id" => $myrow["project_id"],
                "project_description" => $myrow["project_description"],
                "float_id" => $myrow["float_id"],
                "float_name" => $myrow["float_name"],
                "employee_code" => $myrow["employee_code"],
                "company_code" => $myrow["company_code"],
                "type_name" => $myrow["type_name"],
                "tran_date" => $myrow["tran_date"],
                "amount" => $myrow["amount"],
                "comments" => $myrow["comments"],
                "batch_no" => $myrow["batch_no"],
                "batch_approval_status"  => $myrow["batch_approval_status"]);

        $ious[] = $a;
    }

    $result = get_i_owe_yous_for_expenses_entry(true, $iou_id, $batch_no, $from_date, $to_date, $employee_code, $type_id, $project_id, $float_id);
    while ($myrow = db_fetch($result))
    {
        $a = array(
                "id" => $myrow["id"],
                "project_id" => $myrow["project_id"],
                "project_description" => $myrow["project_description"],
                "float_id" => $myrow["float_id"],
                "float_name" => $myrow["float_name"],
                "employee_code" => $myrow["employee_code"],
                "company_code" => $myrow["company_code"],
                "type_name" => $myrow["type_name"],
                "tran_date" => $myrow["tran_date"],
                "amount" => $myrow["amount"],
                "comments" => $myrow["comments"],
                "batch_no" => $myrow["batch_no"],
                "batch_approval_status"  => $myrow["batch_approval_status"]);

        $ious[] = $a;
    }

}

function display_ious_with_expenses($iou_id, $batch_no, $from_date, $to_date, $employee_code, $type_id, $project_id, $float_id)
{
    display_heading("I Owe Yous With Expenses");
    
    start_table(TABLESTYLE, "width=90%");

    $th = array(_("Id"),"Project", _("Employee Name"), "Float", _("Type"),
                _("Date"),_("Amount"), "Comment", "Batch No", "Select");
    table_header($th);

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



    $approval_statuses_in = AS_NEW;

    $ious = array();
    build_ious_with_expenses_array($ious, $iou_id, $batch_no, $from_date, $to_date, $employee_code, $type_id, $project_id, $float_id);

    foreach ($ious as $iou_line) {
        alt_table_row_color($k);

            //label_cells('',$myrow["id"]);

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

        label_cells('',$iou_line["comments"]);
//        label_cells('',$iou_line["batch_no"],'', "align=center");
        label_cell(get_petty_cash_trans_view_str(ST_I_OWE_YOU_BATCH, $iou_line["batch_no"]), "align=center");
//        label_cells('',$iou_line["batch_approval_status"]);

        check_cells('', 'selected_'.$iou_line["id"],0);

        end_row();
//        $j++;
//        If ($j == 12)
//        {
//            $j = 1;
//            table_header($th);
//        }
    }

    end_table(1);
}


function display_new_ious($iou_id, $batch_no, $from_date, $to_date, $employee_code, $type_id, $project_id, $float_id)
{
    display_heading("I Owe Yous Without Expenses");
    
    start_table(TABLESTYLE, "width=90%");

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

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



    $approval_statuses_in = AS_NEW;

    $ious = array();
    build_new_ious_array($ious, $iou_id, $batch_no, $from_date, $to_date, $employee_code, $type_id, $project_id, $float_id);

    foreach ($ious as $iou_line) {
        alt_table_row_color($k);

            //label_cells('',$myrow["id"]);

        label_cells('',get_petty_cash_trans_view_str(ST_I_OWE_YOU, $iou_line["id"]));
        label_cells('',$iou_line["project_description"]);
        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);

        label_cells('',$iou_line["comments"]);
//        label_cells('',$iou_line["batch_no"],'', "align=center");

        check_cells('', 'selected_'.$iou_line["id"],0);

        end_row();
//        $j++;
//        If ($j == 12)
//        {
//            $j = 1;
//            table_header($th);
//        }
    }

    end_table(1);
}






start_form();

br();

start_table();
    start_row();
        ref_cells(text_bold("IOU Id"), 'iou_id', '',null, '', true);
        ref_cells(text_bold("Batch N0"), 'batch_no', '',null, '', true);
        petty_cash_floats_list_cells(_("Float:"), 'float_id', null, _('All floats'));
        value_list_cells("I Owe You Type:", "type_id", "PETTY_CASH_TYPES", null, '');
        date_cells(_("from:"), 'from_date', '', null, -14);
        date_cells(_("to:"), 'to_date');
        
    end_row();
end_table();

start_table();
    start_row();
        project_list_cells(_("Project:"), 'project_id', null, _('All projects'));      
        group_companies_list_cells("Company:", 'group_company_code', null, false, true);
        group_company_employees_simple_list_cells(_("Select an Employee:"), 'employee_code', get_post('group_company_code'), null, "All employees", false);    
    
//        emoplyees_list_cells(_("Select an Employee:"), 'employee_code', null, "All employees");
        
        submit_cells('SearchOrders', _("Search"),'',_('Search'), 'default');

end_row();
end_table(1);

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

$iou_id = 0;
if(isset($_POST['iou_id'])){
    $iou_id = $_POST['iou_id'];
}

$batch_no = 0;
if(isset($_POST['batch_no'])){
    $batch_no = $_POST['batch_no'];
}

$from_date = "";
if(isset($_POST['from_date'])){
    $from_date = $_POST['from_date'];
}
$to_date = "";
if(isset($_POST['to_date'])){
    $to_date = $_POST['to_date'];
}
$employee_code = "";
if(isset($_POST['employee_code'])){
    $employee_code = $_POST['employee_code'];
}
$type_id = 0;
if(isset($_POST['type_id'])){
    $type_id = $_POST['type_id'];
}

$project_id= 0;
if(isset($_POST['project_id'])){
    $project_id = $_POST['project_id'];
}

$float_id= 0;
if(isset($_POST['float_id'])){
    $float_id = $_POST['float_id'];
}

if (isset($_POST['UpdateData'])){
    mark_selected_i_owe_yous($path_to_root, $iou_id, $batch_no, $from_date, $to_date, $employee_code, $type_id, $project_id, $float_id);
}


$Ajax->activate('leaves');

div_start('leaves');

display_ious_with_expenses($iou_id, $batch_no, $from_date, $to_date, $employee_code, $type_id, $project_id, $float_id);

br();


display_new_ious($iou_id, $batch_no, $from_date, $to_date, $employee_code, $type_id, $project_id, $float_id);

div_end();
submit_center('UpdateData', _("Select"), true, false, 'default');

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