<?php
require_once 'includes/db_connect.php';
// We don't have the create_notification function here, so we will do the insert directly.
if (!isset($_SESSION["user_id"])) { header("location: login.php"); exit; }

$message = ''; 
$sender_id = $_SESSION['user_id']; 
$sender_mobile = $_SESSION['mobile'];

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['transaction_pin'])) {
    $receiver_mobile = trim($_POST['receiver_mobile']); 
    $amount = (float)$_POST['amount']; 
    $pin = $_POST['transaction_pin'];

    if (empty($receiver_mobile) || $amount <= 0 || empty($pin)) {
        $message = '<div class="alert alert-danger">অনুগ্রহ করে সব তথ্য সঠিকভাবে পূরণ করুন।</div>';
    } elseif ($receiver_mobile == $sender_mobile) {
        $message = '<div class="alert alert-danger">আপনি নিজের একাউন্টে ব্যালেন্স ট্রান্সফার করতে পারবেন না।</div>';
    } else {
        $conn->begin_transaction();
        try {
            // 1. Get sender's details and lock the row for update
            $stmt_sender = $conn->prepare("SELECT balance, transaction_pin FROM users WHERE id = ? FOR UPDATE");
            $stmt_sender->bind_param("i", $sender_id); 
            $stmt_sender->execute();
            $sender = $stmt_sender->get_result()->fetch_assoc();
            $stmt_sender->close();

            // 2. Verify PIN, then balance
            if (is_null($sender['transaction_pin'])) { throw new Exception("অনুগ্রহ করে প্রথমে প্রোফাইল পেজ থেকে আপনার লেনদেনের পিন সেট করুন।"); }
            if (!password_verify($pin, $sender['transaction_pin'])) { throw new Exception("আপনার দেওয়া পিনটি সঠিক নয়।"); }
            if ($sender['balance'] < $amount) { throw new Exception("আপনার একাউন্টে পর্যাপ্ত ব্যালেন্স নেই।"); }
            
            // 3. Get receiver's details and lock the row for update
            $stmt_receiver = $conn->prepare("SELECT id FROM users WHERE mobile = ? AND role = 'user' FOR UPDATE");
            $stmt_receiver->bind_param("s", $receiver_mobile); 
            $stmt_receiver->execute();
            $receiver_result = $stmt_receiver->get_result();
            if ($receiver_result->num_rows == 0) { throw new Exception("প্রাপকের মোবাইল নম্বরটি খুঁজে পাওয়া যায়নি।"); }
            $receiver_id = $receiver_result->fetch_assoc()['id'];
            $stmt_receiver->close();
            
            // 4. Perform the transfer
            $conn->query("UPDATE users SET balance = balance - $amount WHERE id = $sender_id");
            $conn->query("UPDATE users SET balance = balance + $amount WHERE id = $receiver_id");
            
            // 5. Log transactions for both users
            $sender_desc = "Balance transfer to " . $receiver_mobile;
            $conn->query("INSERT INTO transactions (user_id, type, amount, description) VALUES ($sender_id, 'Balance Transfer', $amount, '$sender_desc')");
            
            $receiver_desc = "Balance received from " . $sender_mobile;
            $conn->query("INSERT INTO transactions (user_id, type, amount, description) VALUES ($receiver_id, 'Balance Received', $amount, '$receiver_desc')");

            // 6. Create a notification for the receiver
            $notification_title = "ব্যালেন্স গ্রহণ";
            $notification_message = "আপনি " . htmlspecialchars($sender_mobile) . " নম্বর থেকে ৳" . number_format($amount, 2) . " গ্রহণ করেছেন।";
            $stmt_notify = $conn->prepare("INSERT INTO notifications (user_id, title, message) VALUES (?, ?, ?)");
            $stmt_notify->bind_param("iss", $receiver_id, $notification_title, $notification_message);
            $stmt_notify->execute();
            $stmt_notify->close();
            
            // 7. If all successful, commit the transaction
            $conn->commit();
            $message = '<div class="alert alert-success">সফলভাবে ৳'.number_format($amount, 2).' টাকা '.htmlspecialchars($receiver_mobile).' নম্বরে পাঠানো হয়েছে।</div>';
        } catch (Exception $e) {
            $conn->rollback();
            $message = '<div class="alert alert-danger">ট্রান্সফার ব্যর্থ: ' . $e->getMessage() . '</div>';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ব্যালেন্স ট্রান্সফার</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        body { background-color: #f4f7fa; font-family: 'Noto Sans Bengali', sans-serif; }
        .transfer-card { background-color: white; border-radius: 1rem; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
        .header-bar { background-color: #0d6efd; color: white; padding: 1rem; border-top-left-radius: 1rem; border-top-right-radius: 1rem; }
    </style>
</head>
<body>
<div class="container my-4" style="max-width: 450px;">
    <div class="transfer-card">
        <div class="header-bar d-flex justify-content-between align-items-center">
            <a href="index.php" class="text-white fs-4 text-decoration-none"><i class="fas fa-arrow-left"></i></a>
            <h5 class="mb-0">ব্যালেন্স ট্রান্সফার</h5>
            <div style="width: 24px;"></div>
        </div>
        <div class="p-3">
            <?php if(!empty($message)) echo $message; ?>
            <form id="transferForm" method="POST" action="balance_transfer.php">
                <div class="mb-3">
                    <label class="form-label fw-bold">প্রাপকের মোবাইল নম্বর</label>
                    <input type="tel" name="receiver_mobile" id="receiverMobile" class="form-control form-control-lg" required>
                    <div id="receiverNameDisplay" class="mt-2 text-success fw-bold"></div>
                </div>
                <div class="mb-3">
                    <label class="form-label fw-bold">টাকার পরিমাণ</label>
                    <input type="number" step="0.01" name="amount" id="transferAmount" class="form-control form-control-lg" required>
                </div>
                <div class="d-grid mt-4">
                    <button type="button" class="btn btn-primary btn-lg" id="checkAccountBtn">পরবর্তী</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="confirmationModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">লেনদেন নিশ্চিত করুন</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>আপনি কি <strong id="confirmName"></strong> (<span id="confirmNumber"></span>) -কে <strong id="confirmAmount"></strong> টাকা পাঠাতে চান?</p>
                <div class="mb-3">
                    <label for="transactionPin" class="form-label">আপনার ৪-সংখ্যার লেনদেন পিন দিন</label>
                    <input type="password" class="form-control" id="transactionPin" inputmode="numeric" maxlength="4" placeholder="••••" required>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
                <button type="button" class="btn btn-success" id="confirmTransferBtn">নিশ্চিত করুন</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
    const checkAccountBtn = document.getElementById('checkAccountBtn');
    const transferForm = document.getElementById('transferForm');
    const confirmationModal = new bootstrap.Modal(document.getElementById('confirmationModal'));

    checkAccountBtn.addEventListener('click', function() {
        const receiverMobile = document.getElementById('receiverMobile').value;
        const amount = document.getElementById('transferAmount').value;
        const receiverNameDisplay = document.getElementById('receiverNameDisplay');
        receiverNameDisplay.innerText = ''; // Clear previous name

        if (!receiverMobile || amount <= 0) {
            alert('অনুগ্রহ করে প্রাপকের নম্বর এবং টাকার পরিমাণ দিন।');
            return;
        }

        // Use fetch to call the API to get user details
        fetch('api/get_user_details.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `mobile=${receiverMobile}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                // Show receiver's name on the main page for confirmation
                receiverNameDisplay.innerText = `প্রাপক: ${data.name}`;
                // Populate and show the confirmation modal
                document.getElementById('confirmName').innerText = data.name;
                document.getElementById('confirmNumber').innerText = receiverMobile;
                document.getElementById('confirmAmount').innerText = `৳${amount}`;
                confirmationModal.show();
            } else {
                // Show error message from the API
                alert(data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('একটি সমস্যা হয়েছে। আবার চেষ্টা করুন।');
        });
    });

    document.getElementById('confirmTransferBtn').addEventListener('click', function() {
        const pin = document.getElementById('transactionPin').value;
        if (!pin || pin.length !== 4) {
            alert('অনুগ্রহ করে আপনার ৪-সংখ্যার সঠিক পিন দিন।');
            return;
        }
        // Add the PIN as a hidden input to the form and submit
        const hiddenPinInput = document.createElement('input');
        hiddenPinInput.type = 'hidden';
        hiddenPinInput.name = 'transaction_pin';
        hiddenPinInput.value = pin;
        transferForm.appendChild(hiddenPinInput);
        transferForm.submit();
    });
</script>
</body>
</html>