<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_PETTY_CASH_REOPEN_IOUS';
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/approval_functions.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/includes/project_cost_functions.inc");

include_once($path_to_root . "/petty_cash/includes/db/reopen_i_owe_yous_db.inc");
include_once($path_to_root . "/petty_cash/includes/db/i_owe_you_db.inc");
include_once($path_to_root . "/petty_cash/includes/db/petty_cash_payments_db.inc");
include_once($path_to_root . "/petty_cash/includes/db/i_owe_you_expenses_db.inc");

//include_once($path_to_root . "/payroll/includes/db/payroll_calculation_db.inc");
//include_once($path_to_root . "/jobq/includes/jobq_requests.inc");
include_once($path_to_root . "/manufacturing/includes/work_order_validations.inc");
include_once($path_to_root . "/includes/db/group_companies_db.inc");

include_once($path_to_root . "/includes/db/group_companies_db.inc");

include_once($path_to_root . "/includes/db/group_companies_db.inc");
include_once($path_to_root . "/includes/common_functions.inc");

include_once($path_to_root . "/includes/db/approval_functions_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 = "Reopen I Owe Yous"), false, false, "", $js);

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

//return;


if (isset($_GET['ReopenedID'])) 
{
	$trans_no = $_GET['ReopenedID'];
	$trans_type = ST_I_OWE_YOU;
        
    $message = get_session_variable("reopen_approved_iou_messages");
    clear_session_variable("reopen_approved_iou_messages");
    
    display_notification_centered($message);
    
//    display_note(sprintf( _("Order # %d has been reopened."),$trans_no),0,2);     

	display_footer_exit();
}

function can_reopen_iou($iou)
{
    if(!($iou['approval_status'] == AS_APPROVED)){
        $msg = "Status of this IOU does not allow reopening it.";
        display_error($msg);
        return false;
    }
    
    if($iou['batch_complete'] == true){
        $msg = "Expenses batch (".$iou['batch_no'].") of this IOU has been completed. It can not be reopened.";
        display_error($msg);
        return false;
    }
    
    if($iou['advances_batch_no'] > 0){
        $msg = "An advance payment has been done for this IOU. It can not be reopened.";
        display_error($msg);
        return false;
    }
    
    $iou_payments_result = get_i_owe_you_payments($iou['id']);
    if(db_num_rows($iou_payments_result) > 0){
        $msg = "There are payments done for this IOU. It can not be reopened.";
        display_error($msg);
        return false;
    }
    
    $batch_result = get_batch_i_owe_you_expences($iou['batch_no']);
    if(db_num_rows($batch_result) > 0){
        $msg = "There are expenses entered for this IOU batch. It can not be reopened.";
        display_error($msg);
        return false;
    }
    
    return true;
}


function reopen_approved_iou($iou_id){
        
    $iou = get_i_owe_you_record($iou_id);
    
    if(!can_reopen_iou($iou)){
        return;
    }

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

    $rad_msg = reopen_approved_document(ST_I_OWE_YOU, $iou_id, $iou['project_id'], 
                        $iou['next_approval_group_id'], $current_user_id, $iou['row_state'],
                        $iou['created_by']);
    if($rad_msg['success'] !== true){
        cancel_transaction();
        display_error($rad_msg['message']);
        return;
    }
    
    $iou_details = get_i_owe_you_details($iou_id);
    $task_costs_summary = array();
    while ($myrow = db_fetch($iou_details)){
        add_to_task_cost($task_costs_summary, $myrow['task_id'], $myrow['amount'], $myrow['amount'], $myrow['amount']);
    }
        
    get_task_cost_details($task_costs_summary);
    
    $rta_msg = remove_task_allocations(ST_I_OWE_YOU, $iou['id'], $task_costs_summary, $current_user_id);
    if($rta_msg['success'] !== true){
        cancel_transaction();
        display_error($rta_msg['message']);
        return;
    }

    $row_state = db_new_row_state($iou['row_state']);
//    $row_state = db_new_row_state($row_state);
    $n = update_reopned_i_owe_you($iou_id, $row_state);
    if($n != 1){
        cancel_transaction();
        display_error("Another user has updated IOU ".$iou_id);
        return;
    }
    
    commit_transaction();
    set_session_variable("reopen_approved_iou_messages", $rad_msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "ReopenedID=$iou_id");
    
}

function display_filtering_controls()
{
    start_table();
        start_row();
        ref_cells("IOU No:", 'iou_id');
            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', '', null, +7);
        end_row();
    end_table();

    start_table();
        start_row();
            project_list_cells(_("Project:"), 'project_id', null, _('All projects'));
            petty_cash_floats_list_cells(_("Float:"), 'float_id', null, _('All floats'));
            emoplyees_list_cells(_("Select an Employee:"), 'employee_code', null, "All employees");

            submit_cells('SearchOrders', _("Search"),'',_('Search'), 'default');
        end_row();
    end_row();
    end_table();

}


function display_reopenable_ious()
{
    $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'];
    }

    $iou_id= 0;
    if(isset($_POST['iou_id'])){
        $iou_id = $_POST['iou_id'];
    }
    
    $result = get_ious_for_reopen($iou_id, $type_id, $project_id, $float_id, $employee_code, 
                    $from_date, $to_date); 
    
    div_start('price_table');
    
    if (db_num_rows($result) == 0)
    {
    	display_note(_("There are no I Owe Yous to reopen."));
    }
    else
    {
        start_table(TABLESTYLE, "width=90%");

		$th = array(_("IOU#"), _("Batch#"), 
                        _("Project"), "Order Date", ("Float"),
                        _("Type"),_("Employee"), _("Total"),_("Comment"),
                         "");

        table_header($th);

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

        while ($myrow = db_fetch($result))
        {
            alt_table_row_color($k);

            $s = get_petty_cash_trans_view_str(ST_I_OWE_YOU, $myrow['id']);
            label_cell($s, "align=center");
            
            $d = get_petty_cash_trans_view_str(ST_I_OWE_YOU_BATCH, $myrow['batch_no']);
            label_cell($d, "align=center");
            label_cell($myrow["project_description"]);
            label_cell(sql2date($myrow["tran_date"]), "align=center");
            
            
            label_cell($myrow["float_name"]);
            label_cell($myrow["type_name"]);
            
            $emp_name = get_group_company_employee_formatted_long_name($myrow["company_code"], $myrow["employee_code"]);
            label_cell($emp_name);

            amount_decimal_cell($myrow["amount"]);
            label_cell($myrow["comments"]);
            

//            label_cell($myrow["approval_status"]);
            //label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");

            select_button_cell("Edit".$myrow['id'], _("Select"), _("Select this IOU to reopen"));

            //label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
                                

            end_row();

            $j++;
            If ($j == 25)
            {
            	$j = 1;
        	table_header($th);
            } //end of page full new headings
        } //end of while loop

        end_table();
    }
    div_end();
}

function display_reopening_iou($selected_id)
{
    global $approval_statuses;
    
    $myrow = view_i_owe_you_header($selected_id);

    
    hidden('id', $myrow['id']); 
    
    start_table(TABLESTYLE2);

    
        
    label_row("Id:", $myrow['id']);
    label_row("Reference:", $myrow['reference']);
    label_row("Type:", $myrow['type_name']);    
    label_row("Project:", $myrow['project_description']);
    
    $cmp_name = get_group_company_name($myrow['company_code']);
    label_row("Company:", $cmp_name);
    
    $emp_name = get_group_company_employee_formatted_long_name($myrow['company_code'], $myrow['employee_code']);
    label_row("Employee:", $emp_name);

    label_row("Float:", $myrow['float_name']);
    label_row("Total Amount:", $myrow['amount']);
    label_row("Date:", $myrow['tran_date']);
    label_row("Comments:", $myrow['comments']);

    $s = get_project_trans_view_str(ST_APPROVAL_LOG, $myrow['id']."&source_type_id=".ST_I_OWE_YOU, "Approval Status");
    label_row($s,$approval_statuses[$myrow['approval_status']]);
    

    end_table(1);

    submit("reopen_iou", "Reopen I Owe You" );
}


if(isset($_POST['SearchOrders'])){
    
    $selected_id = -1;
}

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

    reopen_approved_iou($selected_id);
    
    $selected_id = -1;
}
//--------------------------------------------------------------------------------------------------

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

display_filtering_controls();

br();	




global $Ajax;

$Ajax->activate('price_table');

display_reopenable_ious();

br();
//-----------------------------------------------------------------------------------------------

$_POST['order_no'] = 0;
$_POST['reference'] = "";
$_POST['supp_name'] = "";
$_POST['location_name'] = "";
$_POST['requisition_no'] = 0;
$_POST['ord_date'] = 0;
$_POST['curr_code'] = 0;
    
$dec2 = 6;
if ($Mode =='Edit' && $selected_id > 0)
{
    display_reopening_iou($selected_id);
   
}

hidden('selected_id', $selected_id);


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