<?php
/**********************************************************************
***********************************************************************/

$page_security = 'SA_SUPPLIER_TRANSPORT_INVOICES';
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 . "/includes/approval_functions.inc");
include_once($path_to_root . "/gl/includes/db/gl_db_bank_accounts.inc");
include_once($path_to_root . "/reporting/includes/reporting.inc");
include_once($path_to_root . "/transport/includes/db/supplier_transport_invoices_db.inc");
include_once($path_to_root . "/transport/includes/db/vehicle_allocation_db.inc");
include_once($path_to_root . "/transport/includes/ui/supplier_transport_invoices_ui.inc");

include_once($path_to_root . "/includes/project_cost_functions.inc");
include_once($path_to_root . "/includes/db/approval_functions_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 = "Supplier Transport Invoices"), false, false, "", $js);
simple_page_mode(true);

$sti_no = -1;

if (isset($_GET['STINo']))
{
    $_POST['STINo'] = $_GET['STINo'];
}   
        
if (isset($_POST['STINo']) && $_POST['STINo'] > 0){
    $sti_no = $_POST['STINo'];
}


if (isset($_GET['AddedID'])) 
{
	//return;
        
    $trans_no = $_GET['AddedID'];
    $trans_type = ST_SUPPLIER_TRANSPORT_INVOICES;
    $msg = get_session_variable('sti_messages');
    clear_session_variable('sti_messages'); 
    display_notification_centered($msg);

//	hyperlink_no_params("$path_to_root/inventory/inquiry/material_requisitions_inquiry.php", _("Process &Another Material Requisition"));
//
//	hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=$trans_type&trans_no=$trans_no");
    
//    display_note(print_document_link($trans_no, _("&Print This Material Issue"), true, $trans_type), 0, 0);

    
    
	display_footer_exit();
}


if (isset($_GET['Updated_ID'])) 
{
	//return;
        
    $trans_no = $_GET['Updated_ID'];
	$trans_type = ST_SUPPLIER_TRANSPORT_INVOICES;

	display_notification_centered("Supplier Transport Invoice ".$trans_no." has been created.");

//	hyperlink_no_params("$path_to_root/inventory/inquiry/material_requisitions_inquiry.php", _("Process &Another Material Requisition"));
//
//	hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=$trans_type&trans_no=$trans_no");
    
//  display_note(print_document_link($trans_no, _("&Print This Material Issue"), true, $trans_type), 0, 0);

	display_footer_exit();
}

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



function can_process($sti_no)
{
    global $Refs;
    
    if($sti_no > 0){
        $sti = get_supplier_transport_invoice_record($sti_no);
        if(!($sti['approval_status'] == AS_NEW || $sti['approval_status'] == AS_WITH_THE_APPROVER || $sti['approval_status'] == AS_AWAITING_APPROVAL)){
            display_error("This Supplier Transport Invoice status does not allow further updating.");
            return false;
        }
    }      
            
    if(!$Refs->is_valid($_POST['reference'])){
        display_error(_("Please enter a reference."));
		set_focus('reference');
		return false;
    }
    
    if (!is_new_reference($_POST['reference'], ST_SUPPLIER_TRANSPORT_INVOICES, $sti_no)) 
    {
        display_error( _("The entered reference is already in use."));
        set_focus('reference');
        return false;
    }

    
    if(!($_POST['supplier_id'] > 0)){
        display_error(_("Please select a Supplier."));
		set_focus('supplier_id');
		return false;
    }
    
    if(!(strlen($_POST['supp_inv_ref']) > 0)){
        display_error(_("Please enter Supplier Invoice Reference."));
		set_focus('supp_inv_ref');
		return false;
    }
    
    if(get_supplier_transport_invoice_reference($_POST['supplier_id'], $_POST['supp_inv_ref'], $sti_no)){
        display_error(_("Entered Supplier Reference alreay exists."));
		set_focus('supp_inv_ref');
		return false;
    }
    
    if(!is_date($_POST['tran_date'])){
        display_error(_("Entered Invoice Date is not valid."));
		set_focus('tran_date');
		return false;
    }
    
    if(!is_date($_POST['due_date'])){
        display_error(_("Entered Due Date is not valid."));
		set_focus('due_date');
		return false;
    }
    
    if (!is_date_in_fiscalyear($_POST['due_date'])) {
        display_error(_("The entered date is not in fiscal year."));
                set_focus('due_date');
                return false;
    }
        
    $msg = is_accounting_period_open($_POST['due_date']);
    if ($msg['success'] !== true)
    {
        display_error($msg['message']);
                set_focus('due_date');
                return false;
    }
    
    if(!($_POST['project_id'] > 0)){
        display_error(_("Please select a Project."));
		set_focus('project_id');
		return false;
    }    
    
    if(!($_POST['task_id'] > 0)){
        display_error(_("Please select a Budget."));
		set_focus('task_id');
		return false;
    }
    
    
    $advances_total = 0;
    if($sti_no > 0){
        $advances_total = get_supplier_transport_invoice_advances_total($sti_no);
    }
    else{
        $result1 = get_supplier_transport_invoice_vehicle_allocations($sti_no);
        while ($varow = db_fetch($result1)){
            if(isset($_POST[$varow["id"]."_".'selected_va_'.$varow["id"]])){  
                $advances_total += $varow["paid_amount"];
            }
        }
    }
            
    $select_count = $vrc_total = 0;
    if($sti_no > 0){
        $result2 = get_supplier_transport_invoice_vehicle_running_chart($sti_no);
        while ($myrow = db_fetch($result2)){
            $vrc_total += input_num($myrow["id"]."_vrc_".'supplier_charge');  
            
            $line_bill_reference = $_POST[$myrow["id"]."_vrc_".'bill_reference'];
            if(strlen($line_bill_reference) > 0 && line_bill_reference_exists($_POST["supplier_id"], $line_bill_reference, $myrow["id"])){
                display_error(_("Bill Reference already exists."));
                set_focus($myrow["id"]."_vrc_".'bill_reference');
                return false;
            }
        }
    }
    else{
        $result2 = get_vehicle_running_chart($_POST['from_date'], $_POST['to_date'],
                                            $_POST['search_supplier_id'], $_POST['vehicle_id'], $_POST['plate_no'], $_POST['batch_no']);
        while ($myrow = db_fetch($result2)){
            if(isset($_POST[$myrow["id"]."_".'selected_vrc_'.$myrow["id"]])){  
                $vrc_total += input_num($myrow["id"]."_vrc_".'supplier_charge');
                $select_count++;

                if($myrow["supplier_id"] > 0){
                    if($myrow["supplier_id"] != $_POST["supplier_id"]){
                        display_error(_("Vehicle Running Chart entry ".$myrow["id"]." does not belong to the selected supplier."));
                        set_focus('supplier_id');
                        return false;
                    }
                }
                
                $line_bill_reference = $_POST[$myrow["id"]."_vrc_".'bill_reference'];
                if(strlen($line_bill_reference) > 0 && line_bill_reference_exists($_POST["supplier_id"], $line_bill_reference, $myrow["id"])){
                    display_error(_("Bill Reference already exists."));
                    set_focus($myrow["id"]."_vrc_".'bill_reference');
                    return false;
                }
            }
        }
        
        if(!($select_count > 0)){
            display_error(_("No records selected."));
            set_focus('');
            return false;
        }     
    }
    
    $vrc_total += input_num('other_charges');

    $total = $vrc_total - $advances_total;
    if(!($total > 0)){
        display_error(_("Invoice total has to be positive."));
		set_focus('');
		return false;
    }
        
    if(input_num('other_charges') > 0){
        if(!(strlen($_POST['other_charges_text']) > 0)){
            display_error(_("Please enter a description for other charges."));
            set_focus('other_charges_text');
            return false;
        }
    } 
    
    return true;
}

function can_delete_sti_va_detail($sti_no, $va_id)
{
    return true;
}


function can_delete_sti_vrc_detail($sti_no, $vrc_id)
{
    $vrc_total = 0;
    
    $result2 = get_supplier_transport_invoice_vehicle_running_chart($sti_no);
    while ($myrow = db_fetch($result2)){
        if($myrow["id"] != $vrc_id){
            $vrc_total += $myrow['supplier_charge'];  
        }
    }
    
    $sti = get_supplier_transport_invoice_record($sti_no);
    $vrc_total += $sti['other_charges'];
    
    $advances_total = get_supplier_transport_invoice_advances_total($sti_no);
    
    $total = $vrc_total - $advances_total;
    
    if(!($total > 0)){
        display_error(_("This will send Invoice total negative. Can not remove this Vehicle Running Chart Entry from the Invoice."));
		set_focus('');
		return false;
    }
    
    return true;
}


function save_supplier_transport_invoice($sti_no, $release)
{
    global $Refs;
    
    $new_sti_no = 0;
    $other_charges = input_num('other_charges');
    
    if($sti_no > 0){
        $nh = update_supplier_transport_invoice_header($sti_no, $_POST['reference'], $_POST['supp_inv_ref'], $_POST['tran_date'], 
                                                        0, $_POST['payment_terms'], $_POST['due_date'], $_POST['comments'],
                                                        $_POST['other_charges_text'], $other_charges,
                                                        $_POST['project_id'], $_POST['task_id']);
        if($nh !== 1){
            return array("success" => false, "message" => "Another user has updated Supplier Transport Invoice ".$sti_no);
        }
    }
    else{
        $new_sti_no = add_supplier_transport_invoice_header($_POST['supplier_id'], $_POST['reference'], $_POST['supp_inv_ref'], $_POST['tran_date'], 
                                                        0, $_POST['payment_terms'], $_POST['due_date'], $_POST['comments'],
                                                        $_POST['other_charges_text'], $other_charges,
                                                        $_POST['project_id'], $_POST['task_id']);
    }
    
    if($sti_no > 0){
        // No need to update vehicle allocations. If anything to be removed those are already removed
    }
    elseif($new_sti_no > 0){
        $result1 = get_supplier_transport_invoice_vehicle_allocations(-1);
        while ($varow = db_fetch($result1)){
            if(isset($_POST[$varow["id"]."_".'selected_va_'.$varow["id"]])){  
                $n = add_vehicle_allocation_to_supp_transport_invoice($varow["id"], $new_sti_no);
                if($n !== 1){
                    return array("success" => false, "message" => "Another user has updated vehicle allocation ".$varow["id"]);
                }
            }
        }
    }
    else{
        return array("success" => false, "message" => "Could not create new Supplier Transport Invoice.");
    }
    
    
    if($sti_no > 0){
        $result = get_supplier_transport_invoice_vehicle_running_chart($sti_no);
        while ($myrow = db_fetch($result)){ 
            $supplier_charge = input_num($myrow["id"]."_vrc_".'supplier_charge');
            $bill_reference = get_post($myrow["id"]."_vrc_".'bill_reference');
            if($supplier_charge != $myrow['supplier_charge'] || $bill_reference != $myrow['bill_reference']){
                $n = update_supplier_transport_invoice_vrc_detail($myrow["id"], $supplier_charge, $sti_no, $bill_reference);
                if($n !== 1){
                    return array("success" => false, "message" => "Another user has updated vehile running chart entry.".$myrow["id"]);
                }    
            }
        }
    }
    elseif($new_sti_no > 0){
        $result = get_vehicle_running_chart($_POST['from_date'], $_POST['to_date'],
                                            $_POST['search_supplier_id'], $_POST['vehicle_id'], $_POST['plate_no'], $_POST['batch_no']);    
    
        while ($myrow = db_fetch($result)){
            if(isset($_POST[$myrow["id"]."_".'selected_vrc_'.$myrow["id"]])){  
                $supplier_charge = input_num($myrow["id"]."_vrc_".'supplier_charge');
                $bill_reference = get_post($myrow["id"]."_vrc_".'bill_reference');
                $n = update_supplier_transport_invoice_vrc_detail($myrow["id"], $supplier_charge, $new_sti_no, $bill_reference);
                if($n !== 1){
                    return array("success" => false, "message" => "Another user has updated vehile running chart entry.".$myrow["id"]);
                }
            }
        }
        
        $sti_no = $new_sti_no;
        
    }

    
    $ustit_msg = update_sti_totals($sti_no, $_POST['supplier_id'], $other_charges);
    if($ustit_msg['success'] !== true){
        return $ustit_msg;
    }
    
    $Refs->save(ST_SUPPLIER_TRANSPORT_INVOICES, $sti_no, $_POST['reference']);
    
    if(!$release){
        unset($_POST['other_charges_text']);
        unset($_POST['other_charges']);
    
        if($sti_no == $new_sti_no){ // New STI
            $message = "Supplier Transport Invoice $sti_no has been created.";
        }
        else{
            $message = "Supplier Transport Invoice $sti_no has been updated.";
        }
        return array("success" => true, "trans_no" => $sti_no, "message" => $message);
    }
    
    $rsti_msg = release_supplier_transport_invoice($sti_no);
    if($rsti_msg['success'] !== true){
        return array("success" => false, "trans_no" => $sti_no, "message" => $rsti_msg['message']);
    }
    
    return array("success" => true, "trans_no" => $sti_no, "message" => $rsti_msg['message']);
}
    
function update_sti_totals($sti_no, $supplier_id, $other_charges)
{
    $sti_details_total = calculate_supplier_transport_invoice_details_total($sti_no);
    $sti_total = $sti_details_total + $other_charges;
    
    $supplier = get_supplier($supplier_id);
    $item_taxes_array = calculate_common_item_taxes($sti_total, $supplier['tax_group_id'], $supplier['tax_included']);
    $item_tax_total = 0;
        
    delete_supplier_transport_invoice_taxes($sti_no);
    
    foreach ($item_taxes_array as $tax_detail) {
        if($tax_detail['rate'] > 0){
            add_supplier_transport_invoice_tax_detail($sti_no, $tax_detail['tax_type_id'], $tax_detail['Value'], $tax_detail['tax_type_name'], $tax_detail['rate']);
            $item_tax_total += $tax_detail['Value'];
        }
    }
    
    if(!($sti_total > 0)){
        return array("success" => false, "message" => "Supplier Transport Invoive total is less than zero. Can not update.");
    }
    else{
        if($supplier['tax_included'] == 0){
            $sti_total_excl = $sti_total;
        }
        else{
            $sti_total_excl = $sti_total - $item_tax_total; 
        }
        update_supplier_transport_invoice_header_totals($sti_no, $sti_total_excl, $item_tax_total, $supplier['tax_included']);
    }
    
    return array("success" => true, "trans_no" => $sti_no, "message" => "");
}

function send_sti_back_to_originator($sti_no)
{
    if(!can_process($sti_no)){
        return;
    }
    
    $sti = get_supplier_transport_invoice_record($sti_no);
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $rd_msg = send_back_to_document_originator(ST_SUPPLIER_TRANSPORT_INVOICES, $sti['id'], $sti['project_id'],
                                    $sti['next_approval_group_id'], $current_user_id, $sti['row_state'], 
                                    $sti['created_by']);
    
    if($rd_msg['success'] !== true){
        cancel_transaction();
        display_error($rd_msg['message']);
    }
    else{
        $trans_no = $rd_msg['tran_no'];
//        new_doc_date($_POST['mr_date']);
        set_session_variable('sti_messages', $rd_msg['message']);
        
        meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
    }
}


function reject_sti($sti_no)
{
    if(!can_process($sti_no)){
        return;
    }
    
    $sti = get_supplier_transport_invoice_record($sti_no);
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $rd_msg = reject_document(ST_SUPPLIER_TRANSPORT_INVOICES, $sti['id'], $sti['project_id'],
                    $sti['next_approval_group_id'], $current_user_id, $sti['row_state']);
    
    if($rd_msg['success'] !== true){
        cancel_transaction();
        display_error($rd_msg['message']);
    }
    else{
        $trans_no = $rd_msg['tran_no'];

        set_session_variable('sti_messages', $rd_msg['message']);
        
        meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
    }

}

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

$delete_sti_va = find_submit("Delete_sti_va");
if($delete_sti_va > 0){
    if(can_delete_sti_va_detail($sti_no, $delete_sti_va)){
        begin_transaction();
        delete_supplier_transport_invoice_va_detail($sti_no, $delete_sti_va);
        
        $sti = get_supplier_transport_invoice_record($sti_no);
        $ustit_msg = update_sti_totals($sti_no, $sti['supplier_id'], $sti['other_charges']);
        if($ustit_msg['success'] !== true){
            cancel_transaction();
            display_error($ustit_msg['message']);
        }
        else{
            commit_transaction();
            display_notification('Vehicle Allocation detail has been removed from the invoice.');
        }
    }
}


$delete_sti_vrc = find_submit("Delete_sti_vrc");
if($delete_sti_vrc > 0){
    if(can_delete_sti_vrc_detail($sti_no, $delete_sti_vrc)){
        begin_transaction();
        delete_supplier_transport_invoice_vrc_entry($sti_no, $delete_sti_vrc);
        
        $sti = get_supplier_transport_invoice_record($sti_no);
        $ustit_msg = update_sti_totals($sti_no, $sti['supplier_id'], $sti['other_charges']);
        if($ustit_msg['success'] !== true){
            cancel_transaction();
            display_error($ustit_msg['message']);
        }
        else{
            commit_transaction();
            display_notification('Vehicle Running Chart Entry has been removed from the invoice.');
        }
    }
}
    
if(isset($_POST['Create_STI']) || isset($_POST['Create_Release_STI']))
{       
    $release = false;
    if(isset($_POST['Create_Release_STI'])){
        $release = true;
    }
       
    if(can_process(-1)){  
        begin_transaction();
        $sti_msg = save_supplier_transport_invoice(-1, $release);
        if($sti_msg['success'] !== true){
            cancel_transaction();
            display_error($sti_msg['message']);
        }
        else{
            commit_transaction();
            set_session_variable('sti_messages', $sti_msg['message']);
            meta_forward($_SERVER['PHP_SELF'], "AddedID=".$sti_msg['trans_no']);
        }
    }    
}

if(isset($_POST['Update_STI']) || isset($_POST['Update_Release_STI']))
{       
    $release = false;
    if(isset($_POST['Update_Release_STI'])){
        $release = true;
    }
    
    if(can_process($sti_no)){  
        begin_transaction();
        $sti_msg = save_supplier_transport_invoice($sti_no, $release);
        if($sti_msg['success'] !== true){
            cancel_transaction();
            display_error($sti_msg['message']);
        }
        else{
            commit_transaction();
            set_session_variable('sti_messages', $sti_msg['message']);
            meta_forward($_SERVER['PHP_SELF'], "AddedID=".$sti_no);
        }        
    }
}

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

    send_sti_back_to_originator($sti_no);
        
} 



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

    reject_sti($sti_no);
        
} 

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

global $Ajax;

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

br(); 

$Ajax->activate('sti_header');

div_start('sti_header');
display_sti_header($sti_no);
div_end();

br();

if($sti_no > 0){
    
}
else{
    start_table(TABLESTYLE_NOBORDER);
        ref_cells(_("Batch #:"), 'batch_no', '',null, '', false);
        date_cells("From Date :", 'from_date', '', null, -30);
        date_cells("To Date :", 'to_date', '', null, +30);
        supplier_list_cells("Suppler", "search_supplier_id", null, '');
        vehicles_list_cells("Vehicle :", 'vehicle_id', null, '');
        ref_cells("Plate No :", 'plate_no');

        submit_cells('SearchOrders', _("Search"),'',_('Select documents'), 'default');
    end_table(1);   
}


$advances_total = display_supplier_transport_invoice_vehicle_allocations($sti_no);

//br(1);

display_vehicle_running_chart_grouping_details($sti_no, $advances_total);


br(1);

submit_center_first('Calculate_STI', _("Calculate"), '', 'default');
if($sti_no > 0){
    submit_center_last('Update_STI', _("Update"), '', 'default');
    
    br();
    
    submit_center_first('Update_Release_STI', "Release for Approval", '', 'default');
    submit('Back_To_Originator', 'Back To Originator', true, '', 'default');
    submit_center_last('Reject_STI', "Reject", '', 'default');	
}
else{    
    submit_center_last('Create_STI', _("Create"), '', 'default');
    
    br();
    
    submit_center_first('Create_Release_STI', "Release for Approval", '', 'default');
}

br();

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



?>
