<?php require_once('../auth/auth.php');require_once('../auth/acid_balance.php'); ?>
<?php 
if(isset($_POST['jur_invoice'])){
   $invoice    = $_POST['jur_invoice'];
   $tdate      = $_POST['tdate'].' '.$time;

   $acid       = $_POST['acid'];
   $details    = $_POST['details'];
   $dr_amount  = $_POST['dr_amount'];
   $cr_amount  = $_POST['cr_amount'];


		$chinvoice=mysqli_query($conn,"SELECT invoice FROM transaction WHERE coid='$coid' AND invoice='$invoice' LIMIT 1");
		if (mysqli_num_rows($chinvoice)>0 && $amount < 0.01) {}else {

    for ($i = 0; $i < count($acid); $i++)  {
       $inacid      = $acid[$i];
       $indetails   = $details[$i];
       $indr_amount = $dr_amount[$i];
       $incr_amount = $cr_amount[$i];

       $gcatid= mysqli_fetch_assoc(mysqli_query($conn,"SELECT gcatid FROM accounts WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND acid='$inacid' LIMIT 1"))['gcatid'];

      if ($indr_amount > 0) {
        $amount    = $indr_amount;
        $dr_acid   = $inacid;
        $dr_gcatid = $gcatid;

        $cr_acid   = 0;        
        $cr_gcatid = 0;
      } else if($incr_amount > 0) {
        $amount    = $incr_amount;
        $dr_acid   = 0;
        $dr_gcatid = 0; 

        $cr_acid = $inacid;
        $cr_gcatid = $gcatid;
      } 

      mysqli_query($conn,"INSERT INTO transaction(coid,bid,brid,dr_acid,cr_acid,e_acid,dr_gcatid,cr_gcatid,invoice,ttype,details,note,amount,date,ptime,userid,em_id,active) 
          VALUES ('$coid','$bid','$brid','$dr_acid', '$cr_acid', '$uid', '$dr_gcatid', '$cr_gcatid', '$invoice', 'JUR','$indetails','journal','$amount','$tdate','$time','$uid','$us_em_id','1')") or die(mysqli_error($conn));

        $inacid_balance = balance($inacid)['ac_balance'];
        mysqli_query($conn,"UPDATE accounts SET balance='$inacid_balance' WHERE coid='$coid' AND acid ='$inacid'") or die(mysqli_error($conn));
    }

        $year = date('Y');
        $invoice_parts = explode('-', $invoice);
        $prefix = $invoice_parts[0];
        mysqli_query($conn,"UPDATE voucher_no SET v_no=(v_no + 1) WHERE coid='$coid' AND v_type ='$prefix' AND v_year='$year'") or die(mysqli_error($conn));
			
        if (isset($_POST['email'])) {
        	// Email Part Here
        }

        if (isset($_POST['sms'])) {
        	// SMS Part Here
        }


	}
}
?>
