<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_SALESPDCSINHAND';
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 . "/sales/includes/db/pdcs_in_hand_db.inc");
include_once($path_to_root . "/sales/includes/add_customer_payment.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/admin/db/order_categories_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();
}

if (!@$_GET['popup'])
	page(_($help_context = "Post Dated Cheque Payments"), @$_GET['popup'], false, "", $js);

simple_page_mode(true);

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

function submit_pdc($id)
{
    $info['customer_id'] = $_POST['debtor_no'];
    $info['branch_id'] = $_POST['branch_code'];
    
    $info['bank_account_id'] = $_POST['bank_account_id'];

    $info['payment_date'] = $_POST['payment_date'];
    
    $info['reference'] = $_POST['reference'];
    $info['amount'] = $_POST['amount'];
    $info['comment'] = $_POST['comment'];
    $info['banck_charge'] = 0;
    $info['bank_amount'] = $_POST['amount'];
    $info['discount'] = 0;
    $info['order_category_id'] = $_POST['order_category_id'];

    begin_transaction();
    $cpa_msg = customer_payment_add($info);
    if($cpa_msg["passed"] == false){
        display_error($cpa_msg["message"]);
        cancel_transaction();
    }
    else{
        update_payment_id($id,(int)$cpa_msg["message"]);
        commit_transaction();
        display_notification("Payment no ".$cpa_msg["message"]." created.");
    }
}

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

if ($Mode=='ADD_ITEM' || $Mode=='UPDATE_ITEM' || isset($_POST['SubmitPDC'])) 
{
	//initialise no input errors assumed initially before we test
	$input_error = 0;

	if (strlen($_POST['debtor_no']) == 0) 
	{
		$input_error = 1;
		display_error(_("Please select a customer."));
		set_focus('debtor_no');
	}
        
	if (strlen($_POST['cheque_no']) < 1) 
	{
		$input_error = 1;
		display_error(_("Cheque number can not be blank."));
		set_focus('cheque_no');
	}
        
        if(!is_date($_POST['cheque_date']))
	{
		$input_error = 1;
		display_error(_("Cheque date is not valid a date."));
		set_focus('cheque_no');
	}
        
        if(isset($_POST['SubmitPDC'])){
            if(!$_POST['bank_account_id'] > 0)
            {
		$input_error = 1;
		display_error(_("Please select a banck account."));
		set_focus('bank_account_id');
            }
        }
        
        
	if ($input_error == 0) 
	{
            if ($selected_id != -1) 
            {
                    update_pdc($selected_id, $_POST['debtor_no'], $_POST['branch_code'], 
                                    $_POST['cheque_no'], input_num('amount'), 
                                    $_POST['bank_id'], $_POST['bank_branch'], 
                                    date2sql($_POST['cheque_date']), $_POST['comment']);
                    
                    if(isset($_POST['SubmitPDC'])){
                        submit_pdc($selected_id);
                    }
                    else{
                        display_notification(_('Post dated cheque has been updated'));
                    }
            } 
            else 
            {
                    add_pdc($_POST['debtor_no'], $_POST['branch_code'], 
                                    $_POST['cheque_no'], input_num('amount'), 
                                    $_POST['bank_id'], $_POST['bank_branch'], 
                                    date2sql($_POST['cheque_date']), $_POST['comment']);

                            display_notification(_('New member type has been added'));
            }
    	
		$Mode = 'RESET';
	}
} 

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

function can_delete($selected_id)
{
        $myrow = get_pdc_details($selected_id);
        
        if ($myrow['payment_id'] > 0)
	{
		display_error(_("Cannot delete this PDC. There is a payment generated for this cheque."));
		return false;
	}
	
	return true;
}


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

if ($Mode == 'Delete')
{
	if (can_delete($selected_id))
	{
		delete_pdc($selected_id);
		display_notification(_('Selected PDC has been deleted'));
	}
	$Mode = 'RESET';
}

if ($Mode == 'RESET')
{
	$selected_id = -1;
	$sav = get_post('show_inactive');
	unset($_POST);
	$_POST['show_inactive'] = $sav;
}

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

function get_description($code){
    if($code == 1){
        return "Yes";
    }else{
        return "No";
    }
}

if(get_post('RefreshInquiry'))
{
	$Ajax->activate('doc_tbl');
}


function display_filtering_criteria(){
    
    start_table(TABLESTYLE_NOBORDER);
    start_row();

    if (!@$_GET['popup'])
	customer_list_cells(_("Select a customer: "), 'customer_id', null, true, false, false, !@$_GET['popup']);

    //if (!isset($_POST['from_date']))
        date_cells(_("From:"), 'from_date', '', null, 0);
    
    //if (!isset($_POST['to_date']))
        date_cells(_("To:"), 'to_date', '', null, 7);
        
        three_value_list_cells("Status", "pdc_status", '', '', 0, 'Open', 1, 'Realized', 2, false);

    submit_cells('RefreshInquiry', _("Search"),'',_('Refresh Inquiry'), 'default');
    end_row();
    end_table();

    set_global_customer($_POST['customer_id']);
    
}

start_form();

display_filtering_criteria();
div_start('doc_tbl');

$result = get_pdcs($_POST['customer_id'], $_POST['from_date'], $_POST['to_date'], $_POST['pdc_status']);


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

$th = array(_("Customer Name"),_("Branch Name"),
            _("Cheque No"),_("Amount"),_("Cheque Date"),_("Bank Name"),_("Bank Branch"),
            _("Comment"),_("Pmnt. Id"), "", "");
 
//inactive_control_column($th);
table_header($th);
$total = $k = 0;
while ($myrow = db_fetch($result)) 
{
	
	alt_table_row_color($k);	

	label_cell($myrow["customer_name"]);
        label_cell($myrow["br_name"]);
        label_cell($myrow["cheque_no"]);
        amount_cell($myrow["amount"]);
        label_cell(sql2date($myrow["cheque_date"]));
        label_cell($myrow["bank_name"]);
        label_cell($myrow["bank_branch"]);
        label_cell($myrow["comment"]);
        
        if($myrow["payment_id"] > 0){
            label_cell(get_trans_view_str(ST_CUSTPAYMENT, $myrow["payment_id"]));
            label_cell("");
            label_cell("");
        }
        else {
            label_cell('');
            edit_button_cell("Edit".$myrow['id'], _("Edit"));
            delete_button_cell("Delete".$myrow['id'], _("Delete"));
        }

	end_row();
        
        $total += $myrow["amount"];
}
//inactive_control_row($th);
label_cell("<b>"._("Tatal value of cheques") . "</b>", "align=center colspan=3");
qty_cell($total, true, 2);
label_cell('', "align=center colspan=7");

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

start_table(TABLESTYLE2);

if(!isset($_POST['debtor_no']))
    $_POST['debtor_no'] = "";

$_POST['branch_code']  = "";
$_POST['cheque_no']  = "";
$_POST['bank_id']  = "";
$_POST['bank_branch']  = "";
$_POST['cheque_date']  = "";
$_POST['comment']  = "";


if ($selected_id != -1) 
{
 	if ($Mode == 'Edit') {
		//editing an existing status code

		$myrow = get_pdc_details($selected_id);

		$_POST['debtor_no']  = $myrow["debtor_no"];
                $_POST['branch_code']  = $myrow["branch_code"];
                $_POST['cheque_no']  = $myrow["cheque_no"];
                $_POST['amount']  = $myrow["amount"];
                $_POST['bank_id']  = $myrow["bank_id"];
                $_POST['bank_branch'] = $myrow['bank_branch'];
                $_POST['cheque_date']  = sql2date($myrow["cheque_date"]);
                $_POST['comment']  = $myrow["comment"];
	}
	hidden('selected_id', $selected_id);
} 

customer_list_row("Customer:", 'debtor_no', $_POST['debtor_no'],false, true);
customer_branches_list_row("Branch:", $_POST['debtor_no'], 'branch_code', $_POST['branch_code'], false);
text_row(_("Cheque No:"), 'cheque_no', null, 20, 20);
amount_row("Amount:", 'amount');
date_row("Cheque Date:", 'cheque_date', $_POST['cheque_date']);
value_list_row("Bank Name:", 'bank_id', 'BANKS', $_POST['bank_id']);
text_row(_("Branch:"), 'bank_branch', null, 30, 100);

textarea_row("Comment:", 'comment', $_POST['comment'], 30, 2);
end_table(1);

submit_add_or_update_center($selected_id == -1, '', 'both');

if($selected_id > 0){

        br();
        display_heading("Enter below data when submitting the PDC");
        br();
        start_table(TABLESTYLE2);

        bank_accounts_list_row("Account:", 'bank_account_id',false, false, "");
        date_row("Payment Date:", 'payment_date', $_POST['cheque_date']);

        $reference = "";
        if(isset($_POST['cheque_no']))
            $reference = "PDC_".$_POST['cheque_no'];

        text_row(_("Payment Reference:"), 'reference', $reference, 20, 20);

        order_categories_list_row("Order Category:", "order_category_id", OCT_SALES);
        
        end_table(1);

        submit_center('SubmitPDC', "Update and Submit PDC");
}




end_form();

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

end_page();

?>
