<?php

function add_to_monthly_summary_loans($month_id, $loan_id, $calculation_type, $capital_total, $interest_total, 
                                      $late_interest_total, $loan_balance, $calculation_run_id)
{
    if($capital_total == 0 && $interest_total == 0 && $late_interest_total == 0 && $loan_balance == 0){
        return;
    }
	$sql = "INSERT INTO ".TB_PREF."monthly_summary_loans
                            ( month_id, loan_id, 
                              calculation_type, capital_paid, interest_paid, 
                              late_interest_paid, loan_balance, calculation_run_id ) 
                     
		VALUES( ".db_escape($month_id).",".db_escape($loan_id).",
                        ".db_escape($calculation_type).",".db_escape($capital_total).",".db_escape($interest_total).",
                        ".db_escape($late_interest_total).",".db_escape($loan_balance).",".db_escape($calculation_run_id).")";

	db_query($sql,"add_to_project_monthly_summary");
}


function get_monthly_loan_summary($loan_id, $month_end_date)
{
    $sql="SELECT loan_id, SUM(payment_amount) total_capital_paid,
                SUM(payment_interest_amount) total_interest_paid, 
                SUM(late_interest_amount) total_late_interest_paid  
          FROM ".TB_PREF."company_loan_payments 
               
          WHERE loan_id = ".db_escape($loan_id)."  
                AND tran_date <= ".db_escape($month_end_date);

    $result = db_query($sql,"get_monthly_loan_summary");
    
    return db_fetch($result);
}


function delete_monthly_loan_payment_summary($month_id)
{
    $sql = "DELETE FROM ".TB_PREF."monthly_summary_loans  
            WHERE month_id = ".db_escape($month_id)."";

    db_query($sql,"delete_monthly_loan_payment_summary");
}

function get_monthly_company_loans($month_end_date)
{
    $sql = "SELECT cl.*  
        
            FROM ".TB_PREF."company_loans cl 
            WHERE cl.start_date <= ".db_escape($month_end_date);
    
    return db_query($sql, "get_monthly_company_loans");
}