<?php
session_start();
require_once 'includes/auth_check.php';

// Enable detailed error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$page = 'beneficiaries';
$database = new Database();
$db = $database->getConnection();

$error_message = '';
$success_message = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Basic data collection
        $name = trim($_POST['name'] ?? '');
        $account_number = trim($_POST['account_number'] ?? '');
        
        // Validate minimal required fields
        if (empty($name) || empty($account_number)) {
            $error_message = "Name and account number are required.";
        } else {
            // Extremely simple insert with only required fields
            $stmt = $db->prepare("INSERT INTO beneficiaries (user_id, name, account_number) VALUES (?, ?, ?)");
            $result = $stmt->execute([$_SESSION['user_id'], $name, $account_number]);
            
            if ($result) {
                $success_message = "Beneficiary added successfully!";
            } else {
                $error_message = "Database error: " . implode(", ", $stmt->errorInfo());
            }
        }
    } catch (PDOException $e) {
        $error_message = "Database exception: " . $e->getMessage();
    }
}

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<div class="main-content">
    <div class="container py-4">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="h3 mb-0">Add New Beneficiary (Simplified)</h1>
            <a href="beneficiaries.php" class="btn btn-outline-secondary">Back to Beneficiaries</a>
        </div>

        <?php if (!empty($error_message)): ?>
            <div class="alert alert-danger"><?php echo $error_message; ?></div>
        <?php endif; ?>
        
        <?php if (!empty($success_message)): ?>
            <div class="alert alert-success">
                <?php echo $success_message; ?>
                <div class="mt-3">
                    <a href="beneficiaries.php" class="btn btn-success">Go to Beneficiaries Page</a>
                </div>
            </div>
        <?php else: ?>
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Basic Beneficiary Information</h5>
                </div>
                <div class="card-body">
                    <form method="POST" action="add-beneficiary.php">
                        <div class="mb-3">
                            <label for="name" class="form-label">Beneficiary Name (Required)</label>
                            <input type="text" class="form-control" id="name" name="name" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="account_number" class="form-label">Account Number (Required)</label>
                            <input type="text" class="form-control" id="account_number" name="account_number" required>
                        </div>
                        
                        <button type="submit" class="btn btn-primary">Save Beneficiary</button>
                    </form>
                    <!-- Add this after your existing form in add-beneficiary.php -->
<div class="card mt-4">
    <div class="card-header">
        <h5 class="mb-0">Find Bank Users</h5>
    </div>
    <div class="card-body">
        <div class="mb-3">
            <label for="search_account" class="form-label">Search by Account Number</label>
            <div class="input-group">
                <input type="text" class="form-control" id="search_account" placeholder="Enter account number">
                <button class="btn btn-outline-primary" type="button" id="search_btn">Search</button>
            </div>
        </div>
        
        <div id="search_results" class="mt-3" style="display: none;">
            <!-- Results will be shown here -->
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const searchBtn = document.getElementById('search_btn');
    const searchInput = document.getElementById('search_account');
    const resultsDiv = document.getElementById('search_results');
    const nameInput = document.getElementById('name');
    const accountInput = document.getElementById('account_number');
    const recipientSelect = document.getElementById('recipient_id');
    
    searchBtn.addEventListener('click', function() {
        const accountNumber = searchInput.value.trim();
        if (!accountNumber) return;
        
        // Show loading indicator
        resultsDiv.innerHTML = '<div class="text-center"><div class="spinner-border text-primary" role="status"></div><p class="mt-2">Searching...</p></div>';
        resultsDiv.style.display = 'block';
        
        // Make AJAX request to search for the account
        fetch('search_account.php?account=' + encodeURIComponent(accountNumber))
            .then(response => response.json())
            .then(data => {
                if (data.success && data.user) {
                    // User found
                    resultsDiv.innerHTML = `
                        <div class="alert alert-success">
                            <h6>User Found!</h6>
                            <p><strong>Name:</strong> ${data.user.first_name} ${data.user.last_name}</p>
                            <p><strong>Account:</strong> ${data.user.account_number}</p>
                            <button type="button" class="btn btn-primary btn-sm" id="use_this_account">
                                Use This Account
                            </button>
                        </div>
                    `;
                    
                    // Add event listener to the "Use This Account" button
                    document.getElementById('use_this_account').addEventListener('click', function() {
                        nameInput.value = data.user.first_name + ' ' + data.user.last_name;
                        accountInput.value = data.user.account_number;
                        
                        // If there's a recipient select dropdown, try to select this user
                        if (recipientSelect) {
                            const options = recipientSelect.options;
                            for (let i = 0; i < options.length; i++) {
                                if (options[i].textContent.includes(data.user.account_number)) {
                                    recipientSelect.selectedIndex = i;
                                    // Trigger change event if needed
                                    recipientSelect.dispatchEvent(new Event('change'));
                                    break;
                                }
                            }
                        }
                    });
                } else {
                    // User not found
                    resultsDiv.innerHTML = `
                        <div class="alert alert-warning">
                            No user found with this account number in our bank.
                        </div>
                    `;
                }
            })
            .catch(error => {
                resultsDiv.innerHTML = `
                    <div class="alert alert-danger">
                        An error occurred while searching. Please try again.
                    </div>
                `;
                console.error('Error:', error);
            });
    });
});
</script>

                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<?php include 'includes/footer.php'; ?>
