<script>
function calculateFine() {
	var due_amount = document.getElementById('due_amount'),
		inst_no = document.getElementById('inst_no').value,
		inst_amount = document.getElementById('inst_amount').value,
		total_rec = document.getElementById('total_rec').value,
		// rec_amount = document.getElementById('rec_amount'),
		fine = document.getElementById('fine');
		due_amount = parseInt(due_amount.value);
		fine = parseInt(fine.value);
	// document.getElementById('due_amount').value = due_amount;
	// document.getElementById('rec_amount').value = due_amount + fine;
	document.getElementById('total_amount').value = inst_amount * inst_no + fine;
	document.getElementById('hidden_total_rec').value =  inst_amount * inst_no;
	document.getElementById('total_rec').value = inst_amount * inst_no;
}

function calculateAmount() {
  	var inst_amount = document.getElementById('inst_amount').value,
      	// rec_amount = document.getElementById('rec_amount').value,
      	inst_no = document.getElementById('inst_no').value;
      	show_amount = document.getElementById('show_amount').value;
  	// document.getElementById('rec_amount').value = inst_amount * inst_no;
  	// document.getElementById('show_amount').value = inst_amount * inst_no;
  	document.getElementById('total_amount').value = inst_amount * inst_no;
  	document.getElementById('hidden_total_amount').value = inst_amount * inst_no;
}
</script>

<div class="container" style="margin-top: 20px;margin-bottom:20px;">
  	<form method="get" action="Trans_New">
    	<div class="form-group">
      	<input class="form-control" type="text" placeholder="input A/C no and enter" name="no">
    	</div>
  </form>
</div>

<?php
	$CURRENT_RECURRING_BALANCE = 0;
    if(isset($_GET["no"]) && isset($_GET["type"])&&$_GET["type"]=="Loan"){
        echo '
        <div class="container" style="margin-top: 20px;"> <h5>New Transaction : '.$GLOBALS['post_info'].' </h5><hr></div>
        <div class="container">
        <table class="table table-striped table-bordered table-hover table-responsive">
          	<tr>
				<th>Name</th>
				<th>Phone</th>
				<th>AC No</th>
				<th>Remaining Amount</th>
				<th>Installment</th>
          	</tr>';
        $conn = new mysqli($GLOBALS['host'], $GLOBALS['user'], $GLOBALS['pass'], $GLOBALS['db']);
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
        $sql = "SELECT * FROM `".$GLOBALS['arif_ac']."` WHERE  `AA_ACNO` = '".$_GET["no"]."' ";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
              	$date1 = date_create($row["AA_DATE"]);
              	$date2 = date_create(date("Y/m/d"));
              	$diff = date_diff($date1, $date2);
              	if ($row["AA_ACTYPE"] == 'D'){$diff = $diff->format("%a"); $diff=(int)$diff;$due_i=$diff-$row["AA_NO_OF_PAYPAID"];} else {$diff=$diff->format("%m"); $diff=(int)$diff;$due_i=$diff-$row["AA_NO_OF_PAYPAID"];}
				//$ID=$row["GC_ID"];
          		echo "
				<tr>
					<td>".$row["AA_NAME"]."</td>
					<td>".$row["AA_PHONE"]."</td>
					<td>".$row["AA_ACNO"]."</td>
					<td>".$row["AA_BAL"]. '</td>
					<td>
					<form method="post" enctype="multipart/form-data" id="submitInstallment">
							<input type="hidden" name="FORM_NAME" value="add_installment">';
							if ($due_i > 0 && $_GET['type'] == "Loan") {
								$due_amount = $due_i * $row["AA_INSTALLMENT"];
								$due_amount = intval($due_amount);
								$fine_amount = ($due_amount * 40) / 100;
								$total_amount = $row["AA_INSTALLMENT"] + $fine_amount;
								$total_rec = $row["AA_INSTALLMENT"] * 1;
								echo '
								<table class="table table-bordered">
									<tr>
										<td>
											<input type="hidden" name="AA_ACNO" value="'.$row['AA_ACNO'].'">
											<input type="hidden" name="ins_no" value="'.$due_i. '">
											<small>Due Amount:</small>
											<input type="text" id="due_amount" value="'.$due_amount. '" disabled style="width:50px;border:1px solid red">
											<small>Installment Amount:</small>
											<input type="text" id="inst_amount" value="' . $row['AA_INSTALLMENT'] . '" style="width:50px;">
											<small>No:</small>
											<input type="number" id="inst_no" value="1" min="1" style="width:50px;" onchange="calculateFine()">
											<small>Total received:</small>
											<input type="number" id="total_rec" value="'.$total_rec.'" style="width:50px;" onchange="calculateFine()" disabled>
										</td>
									</tr>
									<tr>
										<td>
											<input type="hidden" id="hidden_total_rec" value="'.$total_rec.'" name="add_i" style="width:50px;" onchange="calculateFine()">
											<small>Fine:</small>
											<input type="number" id="fine" name="fine_amount" value="'.$fine_amount.'" min="0" style="width:50px;border:1px solid red" onchange="calculateFine()">
											<small>Total:</small>
											<input type="text" id="total_amount" value="'.$total_amount. '" disabled style="width:50px;border:1px solid red">
											<input type="submit" class="btn-info" value="Receive" onclick="sendData(event)">
										</td>
									</tr>
								</table>';
							} else
							echo'
							<input type="hidden" id="inst_amount" value="'.$row['AA_INSTALLMENT']. '">
							<small>Amount:</small>
							<input type="text" id="show_amount" value="'.$row['AA_INSTALLMENT']. '" disabled style="width:50px;">
							<small>No:</small>
							<input type="number" id="inst_no" value="1" min="1" style="width:50px;" onchange="calculateAmount()">
							<input type="hidden" name="AA_ACNO" value="'.$row['AA_ACNO']. '">
							<small>Total:</small>
							<input type="text" id="total_amount" value="'.$row['AA_INSTALLMENT'].'" disabled style="width:50px;">
							<input type="hidden" id="hidden_total_amount" name="add_i" value="'.$row['AA_INSTALLMENT'].'">
							<input type="submit" class="btn-info" value="Receive" onclick="sendData(event)">';
							echo '</form></td></tr>';
            }
        } else {echo "Check A/C no.";};
        	$conn->close();
        echo '</table></div>';
    }

  	if(isset($_GET["no"]) && isset($_GET["type"])&&$_GET["type"]=="Recurring"){
    	echo '
    		<div class="container" style="margin-top: 10px;"> <h5>New Transaction : '.$GLOBALS['post_info'].' </h5><hr></div>
    		<div class="container table-responsive">
    			<table class="table table-striped table-bordered table-hover">
      				<tr>
						<th>Name</th>
						<th>Phone</th>
						<th>AC No</th>
						<th>Total Deposit</th>
						<th>Installment</th>
						<th>Receive Amount</th>
      				</tr>';
    $conn = new mysqli($GLOBALS['host'], $GLOBALS['user'], $GLOBALS['pass'], $GLOBALS['db']);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT * FROM `".$GLOBALS['arif_ac']."` WHERE  `AA_ACNO` = '".$_GET["no"]."' ";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
          	$date1 = date_create($row["AA_DATE"]);
			$date2 = date_create(date("Y/m/d"));
			$diff = date_diff($date1, $date2);
			if ($row["AA_ACTYPE"] == 'D'){$diff = $diff->format("%a"); $diff=(int)$diff;$due_i=$diff-$row["AA_NO_OF_PAYPAID"];} else {$diff=$diff->format("%m"); $diff=(int)$diff;$due_i=$diff-$row["AA_NO_OF_PAYPAID"];}
            //$ID=$row["GC_ID"];
			$CURRENT_RECURRING_BALANCE = $row["AA_BAL"];
      	echo "
      		<tr>
				<td>".$row["AA_NAME"].    "</td>
				<td>".$row["AA_PHONE"].  "</td>
				<td>".$row["AA_ACNO"]."</td>
				<td>".$row["AA_BAL"]. "</td>
				<td>".$row["AA_INSTALLMENT"].  '</td>
        		<td>
        			<form method="post" enctype="multipart/form-data" id="submitInstallment">
          				<input type="hidden" name="FORM_NAME" value="add_installment">';
          				if ($due_i > 0 && $_GET['type'] == "Recurring") {
                  			$due_amount = $due_i * $row["AA_INSTALLMENT"];
                  			$due_amount = intval($due_amount);
							$fine_amount = ($due_amount * 20) / 100;
							$total_amount = $row["AA_INSTALLMENT"] + $fine_amount;
							$total_rec = $row["AA_INSTALLMENT"] * 1;
                  			echo '
							<table class="table table-bordered">
								<tr>
									<td>
										<input type="hidden" name="AA_ACNO" value="'.$row['AA_ACNO'].'">
										<input type="hidden" name="ins_no" value="'.$due_i. '">
										<small>Due Amount:</small>
										<input type="text" id="due_amount" value="'.$due_amount. '" disabled style="width:50px;border:1px solid red">
										<small>Installment Amount:</small>
										<input type="text" id="inst_amount" value="' . $row['AA_INSTALLMENT'] . '" style="width:50px;">
										<small>No:</small>
										<input type="number" id="inst_no" value="1" min="1" style="width:50px;" onchange="calculateFine()">
										<small>Total received:</small>
										<input type="number" id="total_rec" value="'.$total_rec.'" style="width:50px;" onchange="calculateFine()" disabled>
									</td>
								</tr>
								<tr>
									<td>
										<input type="hidden" id="hidden_total_rec" value="'.$total_rec.'" name="add_i" style="width:50px;" onchange="calculateFine()">
										<small>Fine:</small>
										<input type="number" id="fine" name="fine_amount" value="'.$fine_amount.'" min="0" style="width:50px;border:1px solid red" onchange="calculateFine()">
										<small>Total:</small>
										<input type="text" id="total_amount" value="'.$total_amount. '" disabled style="width:50px;border:1px solid red">
										<input type="submit" class="btn-info" value="Receive" onclick="sendData(event)">
									</td>
								</tr>
							</table>';
                		} else
							echo '
								<input type="hidden" id="inst_amount" value="'.$row['AA_INSTALLMENT']. '">
								<small>Amount:</small>
								<input type="text" id="show_amount" value="'.$row['AA_INSTALLMENT'].'" disabled style="width:50px;">
								<small>No:</small>
								<input type="number" id="inst_no" value="1" min="1" style="width:50px;" onchange="calculateAmount()">
								<input type="hidden" name="AA_ACNO" value="'.$row['AA_ACNO']. '">
								<small>Total:</small>
								<input type="text" id="total_amount" value="'.$row['AA_INSTALLMENT'].'" disabled style="width:50px;">
								<input type="hidden" id="hidden_total_amount" name="add_i" value="'.$row['AA_INSTALLMENT'].'">
								<input type="submit" class="btn-info" value="Receive" onclick="sendData(event)">';
							echo '</form></td></tr>';
        }
    } else {echo "Check A/C no.";};
    $conn->close();
    echo '</table></div>';
}
?>
<?php
if ($_SESSION['type'] === 'admin' && isset($_GET["no"]) && isset($_GET["type"]) && $_GET["type"] == "Recurring") {
    if (
        $_SERVER['REQUEST_METHOD'] === 'POST'
        && isset($_POST['PAY_LOAN_EMI_FROM_RECURRING'], $_POST['PAY_LOAN_EMI_FROM_RECURRING_ID'], $_POST['DEDUCT_LOAN_AMOUNT'])
        && $_POST['PAY_LOAN_EMI_FROM_RECURRING_ID'] === 'axakassaoxnnxsaoij34866'
    ) {
        $loanEMIAmount = floatval($_POST['DEDUCT_LOAN_AMOUNT']);
        $deductAmount  = -$loanEMIAmount; // negative for recurring deduction
        $paidToLoanAccountNumber = $_POST['LOAN_AC_NUMBER'];
        $accountId = $_GET['no'];

        if (!$accountId) {
            echo "Account number missing";
            exit;
        }

        // ✅ DB connection
        $conn = new mysqli($GLOBALS['host'], $GLOBALS['user'], $GLOBALS['pass'], $GLOBALS['db']);
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }

        // ✅ Check recurring balance first
        $sql = "SELECT AA_BAL FROM `" . $GLOBALS['arif_ac'] . "` WHERE `AA_ACNO` = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("s", $accountId);
        $stmt->execute();
        $stmt->bind_result($CURRENT_RECURRING_BALANCE);
        $stmt->fetch();
        $stmt->close();

        if ($loanEMIAmount > $CURRENT_RECURRING_BALANCE) {
            echo "<div class='container' style=' background-color: #f8d7da; color: #721c24; padding: 12px 20px; border: 1px solid #f5c6cb; border-radius: 5px; font-family: Arial, sans-serif; font-size: 15px; margin: 10px auto; position: relative;'>
					<strong>Error!</strong> Insufficient balance in Recurring account.
					<span style=\" position: absolute; top: 8px; right: 12px; color: #721c24; font-weight: bold; cursor: pointer; \" onclick=\"this.parentElement.style.display='none';\">&times;</span>
				</div>";

            exit;
        }

        // ✅ Begin transaction for atomicity
        $conn->begin_transaction();

        try {
            $table = $GLOBALS['arif_tran'] ?? 'arif_tran';
            $userType = 'admin';

            // Entry 1: Deduction from recurring
            $remarksText1 = "₹$loanEMIAmount deducted from Recurring for Loan A/c $paidToLoanAccountNumber EMI";
            $stmt = $conn->prepare("INSERT INTO `$table` (AT_ADMIN, AT_ACID, AT_AMOUNT, REMARKS) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("ssds", $userType, $accountId, $deductAmount, $remarksText1);
            $stmt->execute();
            $stmt->close();

            // Entry 2: Credit to loan account
			$remarksText2 = "₹$loanEMIAmount credited to Loan A/c $paidToLoanAccountNumber EMI (from Recurring $accountId)";
            $stmt = $conn->prepare("INSERT INTO `$table` (AT_ADMIN, AT_ACID, AT_AMOUNT, REMARKS) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("ssds", $userType, $paidToLoanAccountNumber, $loanEMIAmount, $remarksText2);
            $stmt->execute();
            $stmt->close();

            // Update Loan Account
            $ins_no = 1;
            $sql = "UPDATE `" . $GLOBALS['arif_ac'] . "` SET `AA_BAL` = `AA_BAL` + ?, `AA_NO_OF_PAYPAID` = `AA_NO_OF_PAYPAID` + ? WHERE `AA_ACNO` = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("dis", $loanEMIAmount, $ins_no, $paidToLoanAccountNumber);
            $stmt->execute();
            $stmt->close();

            // Update Recurring Account
            $sql = "UPDATE `" . $GLOBALS['arif_ac'] . "` SET `AA_BAL` = `AA_BAL` - ? WHERE `AA_ACNO` = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ds", $loanEMIAmount, $accountId);
            $stmt->execute();
            $stmt->close();

            // ✅ Commit if everything ok
            $conn->commit();

			echo "<div class='container' style=' background-color: #d4edda; color: #155724; padding: 12px 20px; border: 1px solid #c3e6cb; border-radius: 5px; font-family: Arial, sans-serif; font-size: 15px; margin: 10px auto; position: relative;'>
					<strong>Success!</strong> Loan EMI paid successfully!
					<span style=\" position: absolute; top: 8px; right: 12px; color: #155724; font-weight: bold; cursor: pointer; \" onclick=\"this.parentElement.style.display='none';\">&times;</span>
				</div>";


        } catch (Exception $e) {
            $conn->rollback();
            echo "Error processing EMI payment: " . $e->getMessage();
        }

        $conn->close();
    }
}
?>

<?php if ($_SESSION['type'] === 'admin' && isset($_GET["no"]) && isset($_GET["type"]) && $_GET["type"] == "Recurring") { ?>
    <div class="container">
        <h4>Pay Loan EMI from Recurring balance</h4>
		<div style="display: flex; gap: 20px; flex-direction: row; max-width: 60%;">
			<input class="form-control" type="text" id="acno" placeholder="Enter Account No" />
        	<button class="btn btn-primary" onclick="getAccountDetails()">Get Details</button>
		</div>


        <form id="PAY_LOAN_RECURRING_FORM" method="post" style="display: none; gap: 20px; flex-direction: column; max-width: 60%; margin-top: 30px;">
            <input type="hidden" name="PAY_LOAN_EMI_FROM_RECURRING" value="1">
            <input type="hidden" name="PAY_LOAN_EMI_FROM_RECURRING_ID" value="axakassaoxnnxsaoij34866">

			<div>
				<label for="ACCOUNT_HOLDER_NAME">Account holder Name:</label>
				<input class="form-control" id="ACCOUNT_HOLDER_NAME" name="ACCOUNT_HOLDER_NAME" type="text" readOnly />
			</div>
			
			<div>
				<label for="ACCOUNT_HOLDER_NAME">Recurring Balance:</label>
				<input class="form-control" id="ACCOUNT_HOLDER_NAME" name="ACCOUNT_HOLDER_NAME" type="text" value="<?= $CURRENT_RECURRING_BALANCE ?>" readOnly />
			</div>
            <div>
                <label for="LOAN_AC_NUMBER">Loan Account Number:</label>
                <input class="form-control" id="LOAN_AC_NUMBER" name="LOAN_AC_NUMBER" type="text" required readOnly />
            </div>
            <div>
                <label for="DEDUCT_LOAN_AMOUNT">Deduct Loan Amount:</label>
                <input class="form-control" id="DEDUCT_LOAN_AMOUNT" name="DEDUCT_LOAN_AMOUNT" type="number" required />
            </div>
            <div style="">
                <input class="btn btn-success" type="submit" value="Deduct & Pay Now" />
            </div>
        </form>
    </div>
<?php } ?>


<div class="container" style="margin-top: 70px;">
  	<div class="row">
    	<div class="col-md-2">
      		<h5>Past Transactions::::</h5>
    	</div>
    	<div class="col-md-2">
      		<button class="btn btn-success" onclick="window.location.reload()">Refresh</button>
    	</div>
  	</div><hr>
</div>

<?php

if(isset($_GET["no"])){
  	echo '
  	<div class="container table-responsive">
    	<table class="table table-striped table-bordered table-hover">
      	<tr>
			<th>SL</th>
			<th>Tr No</th>
			<th>TimeStamp</th>
			<th>User</th>
			<th>A/C No</th>
			<th>Amount</th>
      	</tr>';
	$conn = new mysqli($GLOBALS['host'], $GLOBALS['user'], $GLOBALS['pass'], $GLOBALS['db']);
    if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);
    //    $sql = "SELECT * FROM `".$GLOBALS['arif_tran']."` WHERE  `AT_ACID` =  '".$_GET['no']."'";
    $sql = "SELECT * FROM `".$GLOBALS['arif_tran']."` WHERE  `AT_ACID` =  '".$_GET['no']."'  ORDER BY `".$GLOBALS['arif_tran']."`.`AT_ID` DESC";
    $result = $conn->query($sql);
    $rowcount=mysqli_num_rows($result);//$rowcount++;
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            //$ID=$row["GC_ID"];
			$kolkataTime = date("d M Y, h:i A", strtotime($row["AT_TIMESTAMP"] . " +5 hours 30 minutes"));
            echo "
            <tr>
				<td>".$rowcount.    "</td>
				<td>".$row["AT_ID"].    "</td>
				<td>".$kolkataTime.  "</td>
				<td>".$row["AT_ADMIN"]. "</td>
				<td>".$row["AT_ACID"].   "</td>
				<td>".$row["AT_AMOUNT"].   "</td>
            </tr>";
            $rowcount--;
        }
    } else echo "No Past record Found";
    mysqli_free_result($result);$conn->close();
    echo '</table></div>';
}
?>

<script>

function getAccountDetails() {
    let acno = document.getElementById("acno").value;

    fetch("/exe/get-loan-details/", {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body: "AA_ACNO=" + encodeURIComponent(acno)
    })
    .then(res => res.json())
    .then(data => {
		document.getElementById('PAY_LOAN_RECURRING_FORM').style.display = 'flex';
        console.log(data.data[0].AA_ACNO);
		document.getElementById('LOAN_AC_NUMBER').value = data.data[0].AA_ACNO;
		document.getElementById('DEDUCT_LOAN_AMOUNT').value = data.data[0].AA_INSTALLMENT;
		document.getElementById('ACCOUNT_HOLDER_NAME').value = data.data[0].AA_NAME;
		document.getElementById('INSTALLMENT_NUMBER').value = data.data[0].AA_BAL / data.data[0].AA_INSTALLMENT;
		
        if(data.status === "Success"){
            // Example: show first record
            console.log("Account Holder: " + data.data[0].AA_NAME + "\nBalance: " + data.data[0].AA_BAL);
        } else {
            alert(data.statusmsg);
        }
    })
    .catch(err => console.error("Error:", err));
}




var submitInstallment = document.getElementById("submitInstallment");
function sendData(event) {
  	event.preventDefault();
  	var XHR = new XMLHttpRequest();
  	var FD = new FormData(submitInstallment);

 	 XHR.addEventListener("load", function (event) {
      	var obj = JSON.parse(event.target.responseText);
      	// console.log(obj);
		alert(obj.statusmsg);
		// window.location.reload(true);
		window.history.back();
  	});

  	XHR.addEventListener("error", function () {
		alert('Error', 'Ooops!! Something went wrong.');
  	});
  	console.log(FD);

  	XHR.open("POST", "/exe/receive_amount/");
  	XHR.send(FD);
}

function addACNumberToField(){
	document.getElementById('LOAN_ACC_NUMBER').value = document.getElementById('LOAN_AC_NUMBER').value;
}


</script>


<!-- GVD20210607R519 -->