<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_PROJECT_BILLING_SCHEDULE';	
$path_to_root = "../..";

include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/sales/includes/sales_db.inc");
include_once($path_to_root . "/sales/includes/db/sales_types_db.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/data_checks.inc");
//include_once($path_to_root . "/inventory/includes/inventory_db.inc");
include_once($path_to_root . "/projects/includes/db/projects_billing_schedule_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();
}

page($help_context = "Project Billing Schedule", false, false, "", $js);

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

check_db_has_projects(_("There are no projects defined in the system."));

simple_page_mode(true);
//---------------------------------------------------------------------------------------------------
$input_error = 0;

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


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

	br(2);
//set_global_stock_item($_POST['project_id']);
function clear_task_data()
{
	unset($_POST['long_description']);
	unset($_POST['description']);
	unset($_POST['start_date']);
	unset($_POST['end_date']);
	unset($_POST['budget']);
	
}
//----------------------------------------------------------------------------------------------------
function can_process()
{
    if(!($_POST['billing_type_id'] > 0)){
        $input_error = 1;
        display_error( _("Billing type can not be empty."));
        set_focus('billing_type_id');
        return false;
    }
    
    if (is_date($_POST['date']) == FALSE)
    {  
        $input_error = 1;
        display_error( _("The entered date is invalid."));
        set_focus('date');
        return false;
    }
    if (check_num('percentage',0) == FALSE){

        $input_error = 1;
        display_error(_("Percentage must be numeric and positive."));
        set_focus('percentage');
        return false;
    } 
    
    if (check_num('amount',0) == FALSE)
    {
        $input_error = 1;
        display_error(_("Amount must be numeric and positive."));
        set_focus('amount');
        return false;
    } 
    
    if (check_num('invoice_no',0) == FALSE)
    {
        $input_error = 1;
        display_error(_("Invalid invoice number."));
        set_focus('invoice_no');
        return false;
    } 
    
    if(input_num('invoice_no') > 0){
        $invoice = get_customer_trans_record(ST_PROJECT_INVOICE, input_num('invoice_no'));
        if(!(isset($invoice['trans_no']) && $invoice['trans_no'] >= 0)){
            $input_error = 1;
            display_error(_("Could not find approved project invoice #".input_num('invoice_no')));
            set_focus('invoice_no');
            return false;
        } 
    } else {
        $_POST['invoice_no'] = 0;
    }
    
    if (check_num('credit_note_no',0) == FALSE)
    {
        $input_error = 1;
        display_error(_("Invalid credit note number."));
        set_focus('credit_note_no');
        return false;
    } 
    
    if(input_num('credit_note_no') > 0){
        $credit_note = get_customer_trans_record(ST_PROJECT_CREDIT_NOTE, input_num('credit_note_no'));
        if(!(isset($credit_note['trans_no']) && $credit_note['trans_no'] >= 0)){
            $input_error = 1;
            display_error(_("Could not find approved project credit note #".input_num('credit_note_no')));
            set_focus('credit_note_no');
            return false;
        } 
    } else {
        $_POST['credit_note_no'] = 0;
    }
    
    if(input_num('invoice_no') > 0 && input_num('credit_note_no') > 0){
        $input_error = 1;
        display_error( _("Please enter either invoice number or credit note number."));
        set_focus('invoice_no');
        return false;
    }
    return true;
}

function display_project_billing_schedule()
{
    start_table(TABLESTYLE_NOBORDER);
        start_row();
        project_list_cells(_("Select a project:"), 'project_id', null,
              _('Select a project'), true, check_value('show_inactive'));
        end_row();
        end_table();


    br(1);    
    $tasks_list = get_project_billing_schedule($_POST['project_id']);



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

    $th = array(_("Type"), _("Date"),_("Percentage %")
                    , _("Amount"), _("Comment"), 
                    _("Invoice No"), _("Credit Note No"), "Inv/CN Date",
                    "Amount", "Allocated", "Ourstanding", "", "");

    table_header($th);

    $k = 0; //row colour counter

    $calculated = false;
    $billing_total = $invoices_total = $paid_total = $outstanding_total = 0;  

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

        label_cell($myrow["billing_type_name"]);
        label_cell(sql2date($myrow["date"]), 'align=center');
        amount_cell($myrow["percentage"]);
        amount_cell($myrow["amount"]); 
        $billing_total += $myrow["amount"];

        label_cell($myrow["comment"]);

        $invoice_amount = $paid_amount = $outstanding_amount = 0;  
        $invoice_date = "";

        $invoice_no = '';
        if ($myrow['invoice_no'] > 0) 
        {
            $invoice_no = $myrow['invoice_no'];
            $invoice = get_customer_trans_record(ST_PROJECT_INVOICE, $invoice_no);
            if(isset($invoice['trans_no']) && $invoice['trans_no'] > 0 ){
                $invoice_amount = $invoice['ov_amount'] + $invoice['ov_gst'] + $invoice['ov_freight'] + $invoice['ov_freight_tax'] - $invoice['ov_discount'];
                $paid_amount = $invoice['alloc'];
                $outstanding_amount = $invoice_amount - $paid_amount; 
                $invoice_date = sql2date($invoice['tran_date']);
            }

        }
        label_cell(get_trans_view_str(ST_PROJECT_INVOICE, $invoice_no), 'align=center');

        $credit_note_no = '';
        if ($myrow['credit_note_no'] > 0) 
        {
            $credit_note_no = $myrow['credit_note_no'];
            $invoice = get_customer_trans_record(ST_PROJECT_CREDIT_NOTE, $credit_note_no);
            if(isset($invoice['trans_no']) && $invoice['trans_no'] > 0 ){
                $invoice_amount -= $invoice['ov_amount'] + $invoice['ov_gst'] + $invoice['ov_freight'] + $invoice['ov_freight_tax'] - $invoice['ov_discount'];
                $paid_amount = -$invoice['alloc'];
                $outstanding_amount = $invoice_amount - $paid_amount;  
                $invoice_date = sql2date($invoice['tran_date']);
            }

        }
        label_cell(get_trans_view_str(ST_PROJECT_CREDIT_NOTE, $credit_note_no), 'align=center');

        if ($myrow['invoice_no'] > 0 || $myrow['credit_note_no'] > 0){
            label_cell($invoice_date, "align=center");
            amount_cell($invoice_amount);
            amount_cell($paid_amount);
            amount_cell($outstanding_amount);
        }
        else{
            label_cell('');
            label_cell('');
            label_cell('');
            label_cell('');
        }

        edit_button_cell("Edit".$myrow['id'], _("Edit"));
        delete_button_cell("Delete".$myrow['id'], _("Delete"));
        end_row();

        $invoices_total += $invoice_amount;
        $paid_total += $paid_amount;
        $outstanding_total += $outstanding_amount;  

    }

    start_row();
        label_cell('Totals', "align=right colspan=3");
        amount_cell($billing_total, true);
        label_cell('', "colspan=4");
        amount_cell($invoices_total, true);
        amount_cell($paid_total, true);
        amount_cell($outstanding_total, true);
        label_cell('', "colspan=2");
    end_row();

    if($_POST['project_id'] > 0){
        $project = get_project_record($_POST['project_id']);
        start_row();
            label_cell('Project Value', "align=right colspan=3");
            amount_cell($project['project_value'], true);
            label_cell('', "colspan=9");
        end_row();
        start_row();
            label_cell('Balance', "align=right colspan=3");
            $balance = ($project['project_value'] - $billing_total);
            if($balance != 0){
                label_cell('<font color="red">'. text_bold(number_format($balance, 2)).'</font>', "align=right");
            }
            else{
                label_cell('');
            }
            label_cell('', "colspan=7");
            end_row();
    }

    end_table();
}

if ($Mode=='ADD_ITEM' && can_process()) 
{
    add_project_billing_schedule_detail($_POST['project_id'], $_POST['billing_type_id'], $_POST['date'],
            input_num('amount'), input_num('percentage'),
            $_POST['comment'], $_POST['invoice_no'], $_POST['credit_note_no']);
    clear_task_data();
    $msg = _("A new billing schedule detail has been added.");
            
    display_notification($msg);
    $Mode = 'RESET';
	
}
if ($Mode=='UPDATE_ITEM' && can_process()) 
{

    update_project_billing_schedule_detail($selected_id, $_POST['billing_type_id'], $_POST['date'],
                input_num('amount'), input_num('percentage'),
                $_POST['comment'], $_POST['invoice_no'], $_POST['credit_note_no']);
        clear_task_data();
        $msg = _("Selected billing schedule detail has been updated.");
        
        display_notification($msg);
        $Mode = 'RESET';
}
//------------------------------------------------------------------------------------------------------

if ($Mode == 'Delete')
{
	//the link to delete a selected record was clicked
	delete_project_billing_schedule_detail($selected_id);
	display_notification(_("The selected billing schedule detail has been deleted."));
	$Mode = 'RESET';
}

if ($Mode == 'RESET')
{
	$selected_id = -1;
}

//--------------------------------------------------------------------------------------------------------
global $Ajax;





$Ajax->activate('price_table');

div_start('price_table');
display_project_billing_schedule();
div_end();
//------------------------------------------------------------------------------------------------

echo "<br>";

if ($Mode == 'Edit')
{
	$myrow = get_project_billing_schedule_detail($selected_id);
        $_POST['billing_type_id'] = $myrow["billing_type_id"];
        $_POST['date'] = sql2date($myrow["date"]);
        $_POST['amount'] = $myrow["amount"];
        $_POST['percentage'] = $myrow["percentage"];
        $_POST['comment'] = $myrow["comment"];
        $_POST['invoice_no'] = $myrow["invoice_no"];
        $_POST['credit_note_no'] = $myrow["credit_note_no"];
}
else{
        $_POST['amount'] = 0.00;
        $_POST['percentage'] = 0.00;
        $_POST['comment'] = '';
}

hidden('selected_id', $selected_id);
if (@$_GET['popup'])
{
	hidden('_tabs_sel', get_post('_tabs_sel'));
	hidden('popup', @$_GET['popup']);
}

div_start('price_details');

    start_table(TABLESTYLE2);

    value_list_row("Type:", 'billing_type_id', "PROJECT_BILLING_TYPES", null, "Select a type");
    date_row(_("Date:"), 'date',null,null,30);
    //date_row(_("End Date:"), 'end_date',null,null,30);
    amount_row(_("Percentage:"), 'percentage');
    amount_row(_("Amount:"), 'amount');
    textarea_row(_("Comment:"), 'comment', null, 31, 3);
//    amount_row(_("Invoice No:"), 'invoice_no', null, null, null, 0);
    text_row(_("Invoice No:"), 'invoice_no', null, 15, 10);
//    amount_row(_("Invoice No:"), 'invoice_no', null, null, null, 0);
    text_row(_("Credit Note No:"), 'credit_note_no', null, 15, 10);
    end_table(1);

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

div_end();

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