<?php
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include ('includes/function.php');

$zdb = $_SESSION["zdbyear_$dbname"];
mysqli_select_db($conn, $zdb);
date_default_timezone_set("Asia/Kolkata");
$addtime = date("H:i:sa");
$username = $_SESSION["username_" . $dbname];



if (isset($_REQUEST['bankname'])) {

    $accdb = "actran";

    $slvouch = $_REQUEST["vouchno"];
    $bankname = $_REQUEST["bankname"];
    $vouchdt = $_REQUEST["paydate"];
    $party = $_REQUEST["party"];
    $paidfor = $_REQUEST["paidfor"];
    $recvamt = $_REQUEST["recvamt"];

    $qrygrp = mysqli_query($conn, "select `grpcode`, bankinit from accmast where `accode` = '$bankname'") or die(mysqli_error($conn));
    $fetgrp = mysqli_fetch_array($qrygrp);
    $pgrp = $fetgrp['grpcode'];
    $binit = $fetgrp['bankinit'];

    if ($pgrp == "001") {
        $maindb = "bankrecp";
        $source = "BR";
    } else {
        $maindb = "cashrecp";
        $source = "CR";
    }



    $gen1 = mysqli_query($conn, "SELECT MAX(vouchno) AS maxcode FROM `$maindb` LIMIT 0,1 ") or die(mysqli_error($conn));

    if (mysqli_num_rows($gen1) > 0) {
        $vvouch = mysqli_fetch_assoc($gen1);
        $qvouch = $vvouch["maxcode"] + 1;
    } else {
        $qvouch = '1';
    }

    $mvouch = $qvouch;


    mysqli_query($conn, "DELETE FROM `$accdb` WHERE vouchno='$mvouch' AND `source`='$source'") or die(mysqli_error($conn));

    if ($recvamt > 0) {
        $minus_amt = ($recvamt * -1);

        // cash part
        mysqli_query($conn, "INSERT INTO `$accdb`(`date`, vouchno, recpno, source, trnno, bankinit, accode, grpcode, amount,prodtype,actamt,`paidfor`, slvouch)
                    VALUES ('$vouchdt','$mvouch', '$recpno', '$source', '001', '$binit', '$bankname','$pgrp', '$minus_amt','$prodtype','$minus_amt','$paidfor', '$slvouch')") or die(mysqli_error($conn));

        // party part
        mysqli_query($conn, "INSERT INTO `$accdb`(`date`, vouchno, recpno, source, trnno, bankinit, accode, grpcode, amount,prodtype,actamt,`paidfor`, slvouch)
                    VALUES ('$vouchdt','$mvouch', '$recpno', '$source', '002', '$binit', '$party', '010', '$recvamt','$prodtype','$recvamt','$paidfor', '$slvouch')") or die(mysqli_error($conn));
    }

    mysqli_query($conn, "INSERT INTO `$maindb`( vouchno ,`vouchdt`, `bankname`, `bankinit`, `recpno`, `party`, `amount`, `adduser`, `adddate`, `addtime`,`paidfor`, slvouch)
                                       Values ('$mvouch', '$vouchdt', '$bankname', '$binit', '$mvouch', '$party', '$recvamt', '$username', '$date', '$addtime','$paidfor', '$slvouch')") or die(mysqli_error($conn));
  
}
echo $mvouch;
?>