 <?php  
  function balance($get_acid,$enddate=false,$fromdate=false) {
    $coid = $GLOBALS['coid'];
  	if ($enddate===false) {
  		$enddate = $GLOBALS['date'];
  	}
  	
  	if ($fromdate!==false) {
  		$acbal = mysqli_query($GLOBALS['conn'],"SELECT 
  			SUM(COALESCE(CASE WHEN dr_acid = '$get_acid' AND date(date)<'$fromdate' THEN amount END,0)) pr_debit,
  			SUM(COALESCE(CASE WHEN cr_acid = '$get_acid' AND date(date)<'$fromdate' THEN amount END,0)) pr_credit,
  			SUM(COALESCE(CASE WHEN dr_acid = '$get_acid' AND date(date)<'$fromdate' THEN amount END,0))-SUM(COALESCE(CASE WHEN cr_acid = '$get_acid' AND date(date)<'$fromdate' THEN amount END,0)) pr_balance,
  			SUM(COALESCE(CASE WHEN dr_acid = '$get_acid' THEN amount END,0)) debit,
  			SUM(COALESCE(CASE WHEN cr_acid = '$get_acid' THEN amount END,0)) credit,
  			SUM(COALESCE(CASE WHEN dr_acid = '$get_acid' THEN amount END,0))-SUM(COALESCE(CASE WHEN cr_acid = '$get_acid' THEN amount END,0)) ac_balance
  		    FROM transaction WHERE coid='$coid' AND active=1 AND (dr_acid = '$get_acid' || cr_acid = '$get_acid') AND date(date) <='$enddate' GROUP BY '$get_acid'") or die(mysqli_error($GLOBALS['conn']));
  	} else {
  		$acbal = mysqli_query($GLOBALS['conn'],"SELECT
  			SUM(COALESCE(CASE WHEN dr_acid = '$get_acid' AND date(date)<'$enddate' THEN amount END,0)) pr_debit,
  			SUM(COALESCE(CASE WHEN cr_acid = '$get_acid' AND date(date)<'$enddate' THEN amount END,0)) pr_credit,
  			SUM(COALESCE(CASE WHEN dr_acid = '$get_acid' AND date(date)<'$enddate' THEN amount END,0))-SUM(COALESCE(CASE WHEN cr_acid = '$get_acid' AND date(date)<'$enddate' THEN amount END,0)) pr_balance,
  		    SUM(COALESCE(CASE WHEN dr_acid = '$get_acid' THEN amount END,0)) debit,
  		    SUM(COALESCE(CASE WHEN cr_acid = '$get_acid' THEN amount END,0)) credit,
  		    SUM(COALESCE(CASE WHEN dr_acid = '$get_acid' THEN amount END,0))-SUM(COALESCE(CASE WHEN cr_acid = '$get_acid' THEN amount END,0)) ac_balance
  		    FROM transaction WHERE coid='$coid' AND active=1 AND (dr_acid = '$get_acid' || cr_acid = '$get_acid') AND date(date) <='$enddate' GROUP BY '$get_acid'") or die(mysqli_error($GLOBALS['conn']));
  	}
     return mysqli_fetch_assoc($acbal);
   }


  function invbalance($get_acid,$date,$tid) {
      $coid = $GLOBALS['coid'];
  		$inbal = mysqli_query($GLOBALS['conn'],"SELECT 
  			SUM(COALESCE(CASE WHEN dr_acid = '$get_acid' THEN amount END,0))-SUM(COALESCE(CASE WHEN cr_acid = '$get_acid' THEN amount END,0)) pr_due
  		    FROM transaction WHERE coid='$coid' AND active=1 AND (dr_acid = '$get_acid' || cr_acid = '$get_acid') AND date(date) <= '$date' AND tid < $tid GROUP BY '$get_acid'") or die(mysqli_error($GLOBALS['conn']));
     return mysqli_fetch_assoc($inbal);
   } 

?>