<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_SUPPPDCSISSUED';
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 . "/purchasing/includes/upload_supplier_payment.inc");
include_once($path_to_root . "/purchasing/includes/db/pdcs_issued_db.inc");
include_once($path_to_root . "/purchasing/includes/db/upload_supplier_payment_db.inc");

include_once($path_to_root . "/includes/ui.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)
{
    if (@$_POST['amount'] == "") 
    {
            $_POST['amount'] = price_format(0);
    }
        
    $info['supplier_id'] = $_POST['supplier_id'];
    $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;

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

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

if((get_post('RefreshInquiry')) || isset($_POST['update']))
{
	//$Ajax->activate('doc_tbl');
}
$Ajax->activate('doc_tbl');
$Ajax->activate('controls');


//if(isset($_POST['add']) || isset($_POST['update']) || isset($_POST['SubmitPDC'])) 
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['supplier_id']) == 0) 
	{
		$input_error = 1;
		display_error(_("Please select a supplier."));
		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(!$_POST['bank_account_id'] > 0)
        {
            $input_error = 1;
            display_error(_("Please select a banck account."));
            set_focus('bank_account_id');
        }
        
        if(isset($_POST['SubmitPDC'])){
            if(strlen($_POST['reference']) < 1)
            {
                $input_error = 1;
                display_error(_("Please enter a reference."));
                set_focus('bank_account_id');
            }
            
            if(!is_date($_POST['payment_date']))
            {
		$input_error = 1;
		display_error(_("Cheque date is not valid a date."));
		set_focus('cheque_no');
            }
        }
        
	if ($input_error == 0) 
	{
            if ($selected_id != -1) 
            {
                    update_issued_pdc($selected_id, $_POST['supplier_id'],  
                                    $_POST['cheque_no'], input_num('amount'), 
                                    $_POST['bank_account_id'], 
                                    date2sql($_POST['cheque_date']), $_POST['comment']);
                    
                    if(isset($_POST['SubmitPDC'])){
                        submit_pdc($selected_id);
                    }
                    else{
                        //clear_data();
                        display_notification(_('Post dated cheque has been updated'));
                    }
            } 
            else
            {
                    add_issued_pdc($_POST['supplier_id'],  
                                    $_POST['cheque_no'], input_num('amount'), 
                                    $_POST['bank_account_id'], 
                                    date2sql($_POST['cheque_date']), $_POST['comment']);

                    display_notification(_('Post dated cheque has been added'));
            }
            


    	
		
                $Mode = 'RESET';
	}
} 

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

function clear_data()
{
    unset($_POST['cheque_no']);
    unset($_POST['amount']);
    unset($_POST['comment']);
    
}

function can_delete($selected_id)
{
        $myrow = get_issued_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_issued_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 display_filtering_criteria(){
    
    start_table(TABLESTYLE_NOBORDER);
    start_row();

    if (!@$_GET['popup'])
	supplier_list_cells(_("Select a Supplier: "), 'supp_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, 'Paid', 2, false);

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

    set_global_supplier($_POST['supp_id']);
    
}

start_form();

display_filtering_criteria();
div_start('doc_tbl');

$result = get_issued_pdcs($_POST['supp_id'], $_POST['from_date'], $_POST['to_date'], $_POST['pdc_status']);


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

$th = array(_("Supplier Name"),
            _("Cheque No"),_("Amount"),_("Cheque Date"),_("Comment"),
            _("Bank Account Name"),_("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["supp_name"]);
        label_cell($myrow["cheque_no"]);
        amount_cell($myrow["amount"]);
        label_cell(sql2date($myrow["cheque_date"]));
        label_cell($myrow["comment"]);
        label_cell($myrow["bank_account_name"]);
        
        if($myrow["payment_id"] > 0){
            label_cell(get_trans_view_str(ST_SUPPAYMENT, $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=2");
qty_cell($total, true, 2);
label_cell('', "align=center colspan=6");
end_table(1);
div_end();
//-----------------------------------------------------------------------------------

start_table(TABLESTYLE2);

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

$_POST['cheque_no']  = "";
$_POST['bank_account_id']  = "";
$_POST['cheque_date']  = "";
$_POST['comment']  = "";


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

		$myrow = get_issued_pdc_details($selected_id);

		$_POST['supplier_id']  = $myrow["supplier_id"];
                $_POST['cheque_no']  = $myrow["cheque_no"];
                $_POST['amount']  = $myrow["amount"];
                $_POST['bank_account_id']  = $myrow["bank_account_id"];
                $_POST['cheque_date']  = sql2date($myrow["cheque_date"]);
                $_POST['comment']  = $myrow["comment"];
	}
	hidden('selected_id', $selected_id);
} 

hidden('id', $selected_id);

supplier_list_row("Supplier:", 'supplier_id', $_POST['supplier_id'],false, true);
text_row(_("Cheque No:"), 'cheque_no', null, 20, 20);
amount_row("Amount:", 'amount');
date_row("Cheque Date:", 'cheque_date', $_POST['cheque_date']);
textarea_row("Comment:", 'comment', $_POST['comment'], 30, 2);
bank_accounts_list_row("Bank Account:", 'bank_account_id', $_POST['bank_account_id']);

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);

        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);

        end_table(1);

        submit_center('SubmitPDC', "Update and Submit PDC");
}
div_start('controls');
//if($selected_id > 1){
//    submit_center('add', _("Add New"), true, '', 'default');
//}
//else{
//    //submit_center('update', _("Update Item"), true, '', 'default');
//    submit_center_first('update', _("Update Item"), '','default');          
//    submit('SubmitPDC', _("Submit PDC"), true, '', true);
//    submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
//}
div_end();

end_form();

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

end_page();

?>
