<?php
include '../connection.php';

session_start(); // Ensure session is started

if (!isset($_SESSION['userid'])) {
    if (isset($_COOKIE['userid'])) {
        $_SESSION['userid'] = $_COOKIE['userid'];
    } else {
        header("Location: ../login.php");
        exit();
    }
}

$Recverid = $_GET['userid'] ?? 0;

// Prepare SQL statement to check if the receiver exists
$sql = "SELECT * FROM student WHERE userid = ?";
$stmt = $con->prepare($sql);
$stmt->bind_param("i", $Recverid);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();

if (!$row) {
    die('No Reseller Found with this ID.');
}

// The rest of your code goes here...

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $userid = $_SESSION['userid']; // Sender ID
    $amount = $_POST['amount'];
    $note = $_POST['note'];
    $pin = $_POST['pin'];
    $status = "Successful";
    $date = date('Y-m-d');

    // Check the balance for the user
    $sqlCheckBalance = "SELECT amount FROM balance WHERE userid = ?";
    $stmtCheckBalance = $con->prepare($sqlCheckBalance);
    $stmtCheckBalance->bind_param("i", $userid);
    $stmtCheckBalance->execute();
    $stmtCheckBalance->bind_result($balance);
    $stmtCheckBalance->fetch();
    $stmtCheckBalance->close();

    // Check the PIN from the student table
    $sqlCheckPin = "SELECT pin FROM student WHERE userid = ?";
    $stmtCheckPin = $con->prepare($sqlCheckPin);
    $stmtCheckPin->bind_param("i", $userid);
    $stmtCheckPin->execute();
    $stmtCheckPin->bind_result($storedPin);
    $stmtCheckPin->fetch();
    $stmtCheckPin->close();

    // Validate the conditions
    if ($balance >= $amount) {
        if ($storedPin === $pin) {
            // Prepare the SQL statement to insert into the send_reseller_history table
            $sqlInsertTopup = "INSERT INTO send_reseller_history (userid, to_user, taka, note, date, status) VALUES (?, ?, ?, ?, ?, ?)";
            $stmtInsertTopup = $con->prepare($sqlInsertTopup);
            $stmtInsertTopup->bind_param("iissss", $userid, $Recverid, $amount, $note, $date, $status);
            $stmtInsertTopup->execute();

            // Deduct the amount from sender's balance
            $sqlDeductBalance = "UPDATE balance SET amount = amount - ? WHERE userid = ?";
            $stmtDeductBalance = $con->prepare($sqlDeductBalance);
            $stmtDeductBalance->bind_param("si", $amount, $userid);
            $stmtDeductBalance->execute();

            // Update or insert the receiver's balance
            $sqlCheckReceiverBalance = "SELECT amount FROM balance WHERE userid = ?";
            $stmtCheckReceiverBalance = $con->prepare($sqlCheckReceiverBalance);
            $stmtCheckReceiverBalance->bind_param("i", $Recverid);
            $stmtCheckReceiverBalance->execute();
            $stmtCheckReceiverBalance->bind_result($receiverBalance);
            $stmtCheckReceiverBalance->fetch();

            if ($receiverBalance !== null) {
                // User exists, update the amount
                $newReceiverAmount = $receiverBalance + $amount;
                $sqlUpdateReceiverBalance = "UPDATE balance SET amount = ? WHERE userid = ?";
                $stmtUpdateReceiverBalance = $con->prepare($sqlUpdateReceiverBalance);
                $stmtUpdateReceiverBalance->bind_param("si", $newReceiverAmount, $Recverid);
                $stmtUpdateReceiverBalance->execute();
            } else {
                // User does not exist, insert a new record
                $sqlInsertReceiverBalance = "INSERT INTO balance (userid, amount) VALUES (?, ?)";
                $stmtInsertReceiverBalance = $con->prepare($sqlInsertReceiverBalance);
                $stmtInsertReceiverBalance->bind_param("is", $Recverid, $amount);
                $stmtInsertReceiverBalance->execute();
            }

            $_SESSION['message'] = "রিকোয়েস্ট সফল হয়েছে"; // Request successful
            $stmtInsertTopup->close();
        } else {
            $_SESSION['message'] = "আপনার পিন নম্বর সঠিক নয়"; // Your PIN number is incorrect
        }
    } else {
        $_SESSION['message'] = "আপনার অ্যাকাউন্টে পর্যাপ্ত টাকা নেই"; // You do not have sufficient balance in your account
    }

    // Close connection
    $con->close();

    // Redirect back to the appropriate page
    header("Location: index.php");
    exit();
}
?>

<?php include 'header-link.php' ?>

<main>

	<?php include 'top-bar.php' ?>

    <section>
        <div class="container mt-2 pb-5">
            <div class="row justify-content-center">
                <div class="col-md-6">
                    <div class="card custom-card">
                        <div class="card-body">
                            <h5 class="card-title text-center"> রিসেলারকে সেন্ড মানি নিশ্চিত করুন </h5>
                            <div class="offer-list p-3">
                                <div class="offer-card mb-2 p-3">
                                    <div class="row flex-row">
                                        <div class="col-md-12 text-center">
                                            <strong class="fw-bold"> নাম : <?php echo htmlspecialchars($row['username']); ?> </strong><br>
                                            <p> নাম্বার : <?php echo htmlspecialchars($row['number']); ?> </p>
                                        </div>
                                    </div>    
                                </div>
                            </div>                

                            <div class="my-3">
                                <form class="form" action="" method="POST">
                                    <div class="mb-1">
                                        <label for="inputField" class="form-label"> টাকার পরিমাণ </label>
                                        <input type="number" min="100" class="form-control" name="amount" id="inputField" placeholder=" টাকার পরিমাণ..." required>
                                        <center>
                                            <small> সর্বনিম্ন পরিমাণ ১০০ টাকা ! অ্যাকাউন্টে পর্যাপ্ত পরিমাণ টাকা না থাকলে লেনদেন সম্পন্ন হবে না </small>
                                        </center>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="note" class="form-label"> নোট </label>
                                        <input type="text" class="form-control" name="note" id="note" placeholder=" নোট ..." required>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="pinField" class="form-label"> পিন </label>
                                        <input type="text" class="form-control" name="pin" id="pinField" placeholder=" পিন..." required>
                                    </div>
                                    
                                    <div class="d-grid">
                                        <button type="submit" class="btn custom-button w-50 mx-auto mb-4"> কনফার্ম করুন </button>
                                    </div>
                                </form>    
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</main>
</body>
</html>
