<?php require_once('../auth/auth.php');require_once('../auth/acid_balance.php'); ?>
<?php 
if(isset($_POST['gcatid'])){
   $gcatid     = $_POST['gcatid'];
   $ac_name    = $_POST['ac_name'];
   $ac_alise   = $_POST['ac_alise'];
   $ac_number  = $_POST['ac_number'];
   $ac_details = $_POST['ac_details'];
   $ac_email   = $_POST['ac_email'];
   $opdate     = $_POST['opdate'].' '.$time;

    mysqli_query($conn,"INSERT INTO accounts(coid,bid,brid,gcatid,ac_name,ac_alise,ac_number,ac_details,ac_email,opdate,atime,userid) 
        VALUES ('$coid','$bid','$brid','$gcatid', '$ac_name', '$ac_alise', '$ac_number', '$ac_details', '$ac_email', '$opdate', '$time', '$uid')") or die(mysqli_error($conn));
    $lastid = mysqli_insert_id($conn);

	if($_POST['balance'] > 0 && $lastid > 0){
		$ttype      = $_POST['ttype'];
		$balance    = $_POST['balance'];
        $tdate      = $co_f_year_start.' '.$time;
		$invoice    = $_POST['invoice'];

        $op_row= mysqli_fetch_assoc(mysqli_query($conn,"SELECT acid,gcatid FROM accounts WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND ac_type='opening' LIMIT 1"));

			if ($ttype == '+') {
				$dr_acid = $lastid;
				$cr_acid = $op_row['acid'];

				$dr_gcatid = $gcatid;
				$cr_gcatid = $op_row['gcatid'];
			} else {
				$dr_acid = $op_row['acid'];
				$cr_acid = $lastid;

				$dr_gcatid = $op_row['gcatid'];
				$cr_gcatid = $gcatid;
			}

	$chinvoice=mysqli_query($conn,"SELECT invoice FROM transaction WHERE coid='$coid' AND invoice='$invoice' LIMIT 1");
		if (mysqli_num_rows($chinvoice)>0) {}else {
           
         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', 'OP','Opening Balance','opening','$balance','$tdate','$time','$uid','$us_em_id','1')") or die(mysqli_error($conn));

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

if (isset($_POST['ac_img_id'])) {
    $ac_img_id=$_POST['ac_img_id'];
    $dataurl = base64_encode(file_get_contents($_POST['dataurl']));
    mysqli_query($conn,"UPDATE accounts SET picture='$dataurl' WHERE coid='$coid' AND acid='$ac_img_id'") or die(mysqli_error($conn));
}
?>