<?php require_once('auth.php'); ?>
<?php
mysqli_query($conn,"UPDATE accounts SET balance = 0 WHERE accounts.coid='$coid'") or die (mysqli_error($conn));
mysqli_query($conn,"UPDATE accounts a
INNER JOIN (
  SELECT acid
  , SUM(COALESCE(CASE WHEN dr_acid=acid THEN amount END,0)) 
  - SUM(COALESCE(CASE WHEN cr_acid=acid THEN amount END,0)) upbalance FROM transaction  INNER JOIN accounts ON (dr_acid = acid || cr_acid = acid)
   WHERE transaction.coid='$coid' AND transaction.active=1 AND (dr_acid = acid || cr_acid = acid) GROUP BY acid HAVING upbalance <> 0)
   x ON (a.acid = x.acid) SET a.balance = x.upbalance WHERE a.coid='$coid'") or die (mysqli_error($conn));

   echo 'Update Complete';
?>