<?php

include('header.php');
$message = '';
$userfound = false;
$userdata = [];

$senderIdentifier = '';
if(isset($udata) && !empty($udata)){
    if(!empty($udata['phone'])) $senderIdentifier = $udata['phone'];
    elseif(!empty($udata['mobileno'])) $senderIdentifier = $udata['mobileno'];
    elseif(!empty($udata['email'])) $senderIdentifier = $udata['email'];
}
if(empty($senderIdentifier) && isset($_SESSION)){
    if(!empty($_SESSION['phone'])) $senderIdentifier = $_SESSION['phone'];
    elseif(!empty($_SESSION['mobileno'])) $senderIdentifier = $_SESSION['mobileno'];
    elseif(!empty($_SESSION['email'])) $senderIdentifier = $_SESSION['email'];
}


$mysqli = null;
if(function_exists('ahkConn')){
    $mysqli = ahkConn();
} elseif(isset($ahk_conn) && $ahk_conn instanceof mysqli){
    $mysqli = $ahk_conn;
}

if(isset($_POST['username'])){
    $username = getSafe($_POST['username']);
    $sql = "SELECT * FROM users WHERE phone='". $username ."' OR email='". $username ."'";
    if(ahkRows($sql)==1){
        $userdata= fetchRow($sql);
        $userfound = true;
        $message = 'User Fetched Successfully! ';
    }else{
        $userfound = false;
        $message = 'No user Found with Associated This Email or Phone';
    }

    // When transaction form submitted
    if(isset($_POST['txn_type']) && isset($_POST['purpose']) && isset($_POST['amount']) && !empty($_POST['amount'])){
        $username = getSafe($_POST['username']);
        $txn_type = getSafe($_POST['txn_type']);
        $purpose = getSafe($_POST['purpose']);
        // sanitize numeric amount (allow decimals)
        $amount = (float) str_replace(',', '', getSafe($_POST['amount']));

        if($amount <= 0){
            $message = 'Please enter a valid amount.';
        } else {
            $sqlBen = "SELECT * FROM users WHERE phone='". $username ."' OR email='". $username ."'";
            if(ahkRows($sqlBen) != 1){
                $message = 'Beneficiary not found.';
            } else {
                $benef = fetchRow($sqlBen); // beneficiary user row

                // For safety, re-fetch sender if transfer
                if($txn_type === 'transfer'){
                    if(empty($senderIdentifier)){
                        $message = 'Sender not identified (session issue). Cannot perform transfer.';
                    } else {
                        $sqlSender = "SELECT * FROM users WHERE phone='".$senderIdentifier."' OR email='".$senderIdentifier."'";
                        if(ahkRows($sqlSender) != 1){
                            $message = 'Sender account not found.';
                        } else {
                            $sender = fetchRow($sqlSender);

                            // Check sender != beneficiary
                            if($sender['phone'] == $benef['phone'] || (!empty($sender['email']) && $sender['email'] == $benef['email'])){
                                $message = 'Cannot transfer to the same account.';
                            } elseif($sender['balance'] < $amount){
                                $message = 'Insufficient balance in sender account.';
                            } else {
                                // Proceed with DB transaction if possible
                                $useTransaction = ($mysqli instanceof mysqli);
                                $success = false;

                                if($useTransaction){
                                    $mysqli->begin_transaction();
                                    try{
                                        // Deduct sender
                                        $sql1 = "UPDATE users SET balance = balance - ? WHERE (phone = ? OR email = ?) AND balance >= ?";
                                        $stmt1 = $mysqli->prepare($sql1);
                                        $stmt1->bind_param('dssd', $amount, $senderIdentifier, $senderIdentifier, $amount);
                                        $stmt1->execute();

                                        if($stmt1->affected_rows != 1){
                                            throw new Exception('Failed to deduct sender balance (possible race/insufficient funds).');
                                        }

                                        // Credit beneficiary
                                        $sql2 = "UPDATE users SET balance = balance + ? WHERE phone = ? OR email = ?";
                                        $stmt2 = $mysqli->prepare($sql2);
                                        $stmt2->bind_param('dss', $amount, $username, $username);
                                        $stmt2->execute();

                                        if($stmt2->affected_rows != 1){
                                            throw new Exception('Failed to credit beneficiary.');
                                        }

                                        // Fetch new balances for history
                                        $qSender = $mysqli->prepare("SELECT balance, phone, email FROM users WHERE phone = ? OR email = ? LIMIT 1");
                                        $qSender->bind_param('ss', $senderIdentifier, $senderIdentifier);
                                        $qSender->execute();
                                        $resS = $qSender->get_result();
                                        $newSender = $resS->fetch_assoc();

                                        $qBen = $mysqli->prepare("SELECT balance, phone, email FROM users WHERE phone = ? OR email = ? LIMIT 1");
                                        $qBen->bind_param('ss', $username, $username);
                                        $qBen->execute();
                                        $resB = $qBen->get_result();
                                        $newBen = $resB->fetch_assoc();

                                        // Insert history rows
                                        $ins1 = $mysqli->prepare("INSERT INTO wallethistory (userid, amount, balance, purpose, status, type) VALUES (?, ?, ?, ?, 1, 'debit')");
                                        $ins1->bind_param('sdds', $newSender['phone'], $amount, $newSender['balance'], $purposeForSender = 'Transfer to '.$newBen['phone'].' ('.$purpose.')');
                                        $ins1->execute();

                                        $ins2 = $mysqli->prepare("INSERT INTO wallethistory (userid, amount, balance, purpose, status, type) VALUES (?, ?, ?, ?, 1, 'credit')");
                                        $ins2->bind_param('sdds', $newBen['phone'], $amount, $newBen['balance'], $purposeForBen = 'Received from '.$newSender['phone'].' ('.$purpose.')');
                                        $ins2->execute();

                                        if($ins1->affected_rows < 1 || $ins2->affected_rows < 1){
                                            throw new Exception('Failed to insert wallet history.');
                                        }

                                        $mysqli->commit();
                                        $success = true;

                                    } catch(Exception $e){
                                        $mysqli->rollback();
                                        $message = 'Transfer failed: '.$e->getMessage();
                                    }

                                } else {
                                    // Fallback without transaction using ahkQuery (best-effort). Make sure order is correct.
                                    $ok1 = ahkQuery("UPDATE users SET balance=balance-{$amount} WHERE phone='".$senderIdentifier."' OR email='".$senderIdentifier."'");
                                    $ok2 = ahkQuery("UPDATE users SET balance=balance+{$amount} WHERE phone='".$username."' OR email='".$username."'");

                                    if($ok1 && $ok2){
                                        // fetch new balances
                                        $newSenderBal = (float)fetchRow("SELECT balance FROM users WHERE phone='".$senderIdentifier."' OR email='".$senderIdentifier."'")[ 'balance' ];
                                        $newBenBal = (float)fetchRow("SELECT balance FROM users WHERE phone='".$username."' OR email='".$username."'")[ 'balance' ];

                                        $h1 = ahkQuery("INSERT INTO wallethistory (userid, amount, balance, purpose, status, type) VALUES ('".$senderIdentifier."','{$amount}','{$newSenderBal}','Transfer to {$username} ({$purpose})','1','debit')");
                                        $h2 = ahkQuery("INSERT INTO wallethistory (userid, amount, balance, purpose, status, type) VALUES ('".$username."','{$amount}','{$newBenBal}','Received from {$senderIdentifier} ({$purpose})','1','credit')");

                                        if($h1 && $h2){
                                            $success = true;
                                        } else {
                                            // Try to rollback naive changes — attempt opposite update if possible
                                            ahkQuery("UPDATE users SET balance=balance+{$amount} WHERE phone='".$senderIdentifier."' OR email='".$senderIdentifier."'");
                                            ahkQuery("UPDATE users SET balance=balance-{$amount} WHERE phone='".$username."' OR email='".$username."'");
                                            $message = 'Transfer failed while recording history. Reverted.';
                                        }
                                    } else {
                                        $message = 'Transfer failed during balance update (no transaction support).';
                                    }
                                }

                                if(!empty($success) && $success === true){
                                    ?>
                                    <script>
                                        $(function(){
                                            Swal.fire(
                                                'Great',
                                                'Transfer Completed Successfully!',
                                                'success'
                                            )
                                        })
                                    </script>
                                    <?php
                                    ahkRedirect('',1200);
                                } else {
                                    // If message not already set by exception, set a generic error
                                    if(empty($message)) $message = 'Unknown error during transfer.';
                                }

                            }
                        }
                    }

                } else if($txn_type === 'credit'){
                    // Admin credits beneficiary
                    $newBen = $benef['balance'] + $amount;
                    $sqlUp = "UPDATE users SET balance=balance+{$amount} WHERE phone='$username' OR email='$username'";
                    $sqlHist = "INSERT INTO `wallethistory`(`userid`, `amount`, `balance`, `purpose`, `status`, `type`) VALUES ('".$benef['phone']."','{$amount}','{$newBen}','{$purpose}','1','credit')";
                    if(ahkQuery($sqlUp) && ahkQuery($sqlHist)){
                        ?>
                        <script>
                            $(function(){
                                Swal.fire(
                                    'Great',
                                    'Amount Credited Successfully!',
                                    'success'
                                )
                            })
                        </script>
                        <?php
                        ahkRedirect('',1200);
                    } else {
                        ?>
                        <script>
                            $(function(){
                                Swal.fire(
                                    'Huuh',
                                    'Transaction Could Not Be Completed!',
                                    'error'
                                )
                            })
                        </script>
                        <?php
                        ahkRedirect('',1200);
                    }

                } else if($txn_type === 'debit'){
                    // Admin debits beneficiary
                    if($benef['balance'] < $amount){
                        $message = 'Beneficiary has insufficient balance for this debit.';
                    } else {
                        $newBen = $benef['balance'] - $amount;
                        $sqlUp = "UPDATE users SET balance=balance-{$amount} WHERE phone='$username' OR email='$username'";
                        $sqlHist = "INSERT INTO `wallethistory`(`userid`, `amount`, `balance`, `purpose`, `status`, `type`) VALUES ('".$benef['phone']."','{$amount}','{$newBen}','{$purpose}','1','debit')";
                        if(ahkQuery($sqlUp) && ahkQuery($sqlHist)){
                            ?>
                            <script>
                                $(function(){
                                    Swal.fire(
                                        'Great',
                                        'Amount Debited Successfully!',
                                        'success'
                                    )
                                })
                            </script>
                            <?php
                            ahkRedirect('',1200);
                        } else {
                            ?>
                            <script>
                                $(function(){
                                    Swal.fire(
                                        'Huuh',
                                        'Transaction Could Not Be Completed!',
                                        'error'
                                    )
                                })
                            </script>
                            <?php
                            ahkRedirect('',1200);
                        }
                    }
                } else {
                    $message = 'Invalid transaction type selected.';
                }

            }
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Transfer Balance</title>
</head>
<body>
		<!--start page wrapper -->
		<div class="page-wrapper">
			<div class="page-content">
				<!--breadcrumb-->
				<div class="page-breadcrumb d-none d-sm-flex align-items-center mb-3">
					<div class="breadcrumb-title pe-3">Transfer Balance to User</div>
					<div class="ps-3">
						<nav aria-label="breadcrumb">
							<ol class="breadcrumb mb-0 p-0">
								<li class="breadcrumb-item"><a href="javascript:;"><i class="bx bx-wallet-alt"></i></a>
								</li>
								<li class="breadcrumb-item active" aria-current="page">Transfer Balance</li>
							</ol>
						</nav>
					</div>
				
				</div>
				<!--end breadcrumb-->
                <?php 
                if($userfound === false){
                    ?>
                    <div class="row">
				<div class="col-xl-10 mx-auto">
					<h6 class="mb-0 text-uppercase">Beneficiary Details</h6>
					<hr/>
					<div class="card border-top border-0 border-4 border-primary">
						<div class="card-body p-5">
                            <?php 
                                        if($message != ''){
                                            ?>
                                            <h5 class="mb-0 text-danger"><?php echo $message; ?></h5><br>
                                            <?php 
                                        }
                                    ?>
							<div class="card-title d-flex align-items-center">
								<div><i class="bx bxs-user me-1 font-22 text-primary"></i>
								</div>
                                   
								<h5 class="mb-0 text-primary">Enter Details</h5>
							</div>
							<hr>
							<form action="" method="POST" class="row g-3">
								<div class="col-md-3">
									<label for="inputFirstName" class="form-label"> Email or Phone</label>
									<input name="username"  type="text"  placeholder="Email or Phone"  class="form-control" id="inputFirstName">
								</div>
								<div class="col-12">
									<button type="submit" class="btn btn-primary px-5">Fetch Details</button>
								</div>
							</form>
						</div>
					</div>
				</div>
			</div>
                    <?php 
                }
                

                // Start User Found Details 
                if($userfound === true){
                    ?>
                    <div class="row">
				<div class="col-xl-10 mx-auto">
					<h6 class="mb-0 text-uppercase">Beneficiary Details</h6>
					<hr/>
					<div class="card border-top border-0 border-4 border-primary">
						<div class="card-body p-5">
                            <?php 
                                if($message != ''){
                                    ?>
                                    <h5 class="mb-0 text-success"><?php echo $message; ?></h5><br>
                                    <?php 
                                }
                                ?>
							<div class="card-title d-flex align-items-center">
								<div><i class="bx bxs-user me-1 font-22 text-primary"></i>
								</div>
                                   
								<h5 class="mb-0 text-primary">Check Payment Details</h5>
							</div>
							<hr>
							<form action="" method="POST" class="row g-3">
								<div class="col-md-3">
									<label for="inputFirstName" class="form-label"> Email or Phone</label>
									<input name="username" value="<?php echo $_POST['username'];?>" type="text" readonly  placeholder="Email or Phone"  class="form-control" id="inputFirstName">
								</div>
								<div class="col-md-3">
									<label for="inputFirstName" class="form-label">Customer Name</label>
									<input name="name" value="<?php echo $userdata['name'];?>"  type="text"  readonly placeholder="Customer Name"  class="form-control" id="inputFirstName">
								</div>
								<div class="col-md-3">
									<label for="inputFirstName" class="form-label">Currect Balance</label>
									<input name="balance" value="<?php echo $userdata['balance'];?>"  type="text"  readonly placeholder="Customer balance"  class="form-control" id="inputFirstName">
								</div>
                                    <br>
								<div class="col-md-3">
									<label for="inputFirstName" class="form-label">Select Transaction Type</label>
									<select class="form-control" name="txn_type">
                                            <option value="">Please Select</option>
                                            <option value="credit">Credit (Admin -> Beneficiary)</option>
                                            <option value="debit">Debit (Beneficiary -> Admin)</option>
                                            <option value="transfer">Transfer (Logged-in User -> Beneficiary)</option>
                                        </select>
								</div>
								<div class="col-md-3">
									<label for="inputFirstName" class="form-label">Select Payment Purpose</label>
									<select class="form-control" name="purpose">
                                            <option value="">Please Select</option>
                                            <option value="deposit">Deposit</option>
                                            <option value="refund">Refund</option>
                                            <option value="penalty">Penalty (for Debit)</option>
                                            <option value="other">Other</option>
                                        </select>
								</div>
                                    <div class="col-md-3">
									<label for="inputFirstName" class="form-label">Enter Amount</label>
									<input name="amount"  type="text"  placeholder="TXN Amount"  class="form-control" id="inputFirstName">
								</div>

								<div class="col-12">
									<button type="submit" class="btn btn-primary px-5">Submit</button>
								</div>
							</form>
						</div>
					</div>
				</div>
			</div>
                    <?php
                }
                ?>
				
				
			</div>
		</div>
		
		<!--end page wrapper -->
		<?php 
		include('footer.php');
		?>
		<!-- Bootstrap JS -->
	

</body>
</html>
