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

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

// Get saved beneficiaries
$stmt = $db->prepare("SELECT b.*, u.first_name, u.last_name, u.account_number FROM beneficiaries b JOIN users u ON b.recipient_id = u.id WHERE b.user_id = ? ORDER BY b.name ASC");
$stmt->execute([$_SESSION['user_id']]);
$beneficiaries = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Check for success/error messages
$success_message = $_SESSION['success_message'] ?? null;
$error_message = $_SESSION['error_message'] ?? null;
unset($_SESSION['success_message'], $_SESSION['error_message']);

// Determine which step to show
$current_step = isset($_GET['step']) ? (int)$_GET['step'] : 1;
if ($current_step < 1 || $current_step > 3) $current_step = 1;

// Store form data in session to persist between steps
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['wizard_action'])) {
    if ($_POST['wizard_action'] === 'step1') {
        $_SESSION['transfer_data'] = [
            'amount' => $_POST['amount'],
            'description' => $_POST['description']
        ];
        header('Location: transfer.php?step=2');
        exit;
    } elseif ($_POST['wizard_action'] === 'step2') {
        $_SESSION['transfer_data']['transferMethod'] = $_POST['transferMethod'];
        if ($_POST['transferMethod'] === 'account') {
            $_SESSION['transfer_data']['accountNumber'] = $_POST['accountNumber'];
        } else {
            $_SESSION['transfer_data']['beneficiaryId'] = $_POST['beneficiaryId'];
        }
        header('Location: transfer.php?step=3');
        exit;
    }
}

// Get user details including currency
$stmt = $db->prepare("SELECT currency FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

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

<style>
    .wizard-progress {
        display: flex;
        justify-content: space-between;
        margin-bottom: 2rem;
        position: relative;
    }
    .wizard-progress::before {
        content: '';
        position: absolute;
        top: 50%;
        left: 0;
        right: 0;
        height: 2px;
        background-color: #e9ecef;
        transform: translateY(-50%);
        z-index: 1;
    }
    .progress-line {
        position: absolute;
        top: 50%;
        left: 0;
        height: 2px;
        background-color: #2563eb;
        transform: translateY(-50%);
        z-index: 2;
        transition: width 0.4s ease;
    }
    .wizard-step-item {
        position: relative;
        z-index: 3;
        text-align: center;
    }
    .step-icon {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background-color: #fff;
        border: 2px solid #e9ecef;
        color: #adb5bd;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 0.5rem;
        transition: all 0.4s ease;
    }
    .wizard-step-item.active .step-icon {
        border-color: #2563eb;
        background-color: #2563eb;
        color: #fff;
    }
    .wizard-step-item.completed .step-icon {
        border-color: #059669;
        background-color: #059669;
        color: #fff;
    }
    .step-label {
        font-size: 0.875rem;
        color: #6c757d;
    }
    .wizard-step-item.active .step-label {
        font-weight: 600;
        color: #2563eb;
    }
    .recipient-card {
        border: 2px solid #e9ecef;
        border-radius: 0.75rem;
        padding: 1rem;
        cursor: pointer;
        transition: all 0.3s ease;
    }
    .recipient-card:hover {
        border-color: #2563eb;
        box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    }
    .recipient-card.selected {
        border-color: #2563eb;
        background-color: rgba(37, 99, 235, 0.05);
    }
</style>

<div class="main-content">
    <div class="page-header mb-4">
        <h4 class="page-title">Transfer Money</h4>
    </div>

    <?php if ($success_message): ?>
        <div class="alert alert-success"><?php echo htmlspecialchars($success_message); ?></div>
    <?php endif; ?>

    <?php if ($error_message): ?>
        <div class="alert alert-danger"><?php echo htmlspecialchars($error_message); ?></div>
    <?php endif; ?>

    <div class="card">
        <div class="card-body p-lg-5">
            <!-- Progress Bar -->
            <div class="wizard-progress">
                <div class="progress-line" style="width: <?php echo (($current_step - 1) / 2) * 100; ?>%"></div>
                <div class="wizard-step-item <?php echo $current_step >= 1 ? 'active' : ''; ?> <?php echo $current_step > 1 ? 'completed' : ''; ?>">
                    <div class="step-icon"><i class='bx bx-dollar'></i></div>
                    <div class="step-label">Amount</div>
                </div>
                <div class="wizard-step-item <?php echo $current_step >= 2 ? 'active' : ''; ?> <?php echo $current_step > 2 ? 'completed' : ''; ?>">
                    <div class="step-icon"><i class='bx bx-user'></i></div>
                    <div class="step-label">Recipient</div>
                </div>
                <div class="wizard-step-item <?php echo $current_step >= 3 ? 'active' : ''; ?>">
                    <div class="step-icon"><i class='bx bx-check-shield'></i></div>
                    <div class="step-label">Confirm</div>
                </div>
            </div>

            <!-- Step 1: Amount -->
            <?php if ($current_step == 1): ?>
                <div class="wizard-step">
                    <h4 class="text-center">How much would you like to send?</h4>
                    <?php
                    // Fetch user's balance from account_balances table
                    $stmt = $db->prepare("SELECT balance FROM account_balances WHERE user_id = ?");
                    $stmt->execute([$_SESSION['user_id']]);
                    $balance = $stmt->fetch(PDO::FETCH_ASSOC);
                    $userBalance = $balance ? $balance['balance'] : 0;
                    ?>
                    <p class="text-center text-muted mb-4">Your available balance is <?php echo htmlspecialchars($user['currency']); ?> <?php echo number_format($userBalance, 2); ?></p>
                    
                    <form method="POST" action="transfer.php">
                        <input type="hidden" name="wizard_action" value="step1">
                        
                        <div class="row justify-content-center">
                            <div class="col-md-6">
                                <div class="input-group input-group-lg mb-3">
                                    <span class="input-group-text"><?php echo htmlspecialchars($user['currency']); ?></span>
                                    <input type="number" class="form-control text-center" name="amount" placeholder="0.00" step="0.01" min="1" required value="<?php echo htmlspecialchars($_SESSION['transfer_data']['amount'] ?? ''); ?>">
                                </div>
                                
                                <div class="mb-3">
                                    <label for="description" class="form-label">Description (Optional)</label>
                                    <input type="text" class="form-control" name="description" placeholder="e.g., For dinner" value="<?php echo htmlspecialchars($_SESSION['transfer_data']['description'] ?? ''); ?>">
                                </div>
                                
                                <div class="d-grid">
                                    <button type="submit" class="btn btn-primary btn-lg">Next</button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            
            <!-- Step 2: Recipient -->
            <?php elseif ($current_step == 2): ?>
                <div class="wizard-step">
                    <h4 class="text-center">Who are you sending money to?</h4>
                    
                    <form method="POST" action="transfer.php">
                        <input type="hidden" name="wizard_action" value="step2">
                        
                        <div class="row justify-content-center">
                            <div class="col-md-8">
                                <ul class="nav nav-pills justify-content-center my-4" id="recipient-tabs" role="tablist">
                                    <li class="nav-item" role="presentation">
                                        <button class="nav-link active" id="account-tab" data-bs-toggle="tab" data-bs-target="#account-pane" type="button" role="tab">Account Number</button>
                                    </li>
                                    <li class="nav-item" role="presentation">
                                        <button class="nav-link" id="beneficiary-tab" data-bs-toggle="tab" data-bs-target="#beneficiary-pane" type="button" role="tab">Beneficiaries</button>
                                    </li>
                                </ul>
                                
                                <div class="tab-content">
                                    <div class="tab-pane fade show active" id="account-pane" role="tabpanel">
                                        <div class="mb-3">
                                            <label class="form-label">Recipient Account Number</label>
                                            <input type="text" class="form-control" name="accountNumber" placeholder="Enter account number" value="<?php echo htmlspecialchars($_SESSION['transfer_data']['accountNumber'] ?? ''); ?>">
                                            <input type="hidden" name="transferMethod" value="account" id="transferMethodAccount">
                                        </div>
                                    </div>
                                    
                                    <div class="tab-pane fade" id="beneficiary-pane" role="tabpanel">
                                        <div class="mb-3">
                                            <label class="form-label">Select Beneficiary</label>
                                            <select class="form-select" name="beneficiaryId">
                                                <option value="">-- Select a beneficiary --</option>
                                                <?php 
                                                // Get all beneficiaries
                                                $stmt = $db->prepare("
                                                    SELECT 
                                                        b.id, 
                                                        b.name, 
                                                        b.recipient_id,
                                                        COALESCE(u.account_number, b.account_number) as account_number,
                                                        b.bank_name,
                                                        b.is_favorite
                                                    FROM 
                                                        beneficiaries b 
                                                    LEFT JOIN
                                                        users u ON b.recipient_id = u.id
                                                    WHERE 
                                                        b.user_id = ? 
                                                    ORDER BY 
                                                        b.is_favorite DESC, b.name ASC
                                                ");
                                                $stmt->execute([$_SESSION['user_id']]);
                                                $all_beneficiaries = $stmt->fetchAll(PDO::FETCH_ASSOC);
                                                
                                                foreach ($all_beneficiaries as $b): 
                                                    $display_name = htmlspecialchars($b['name']);
                                                    $display_account = htmlspecialchars($b['account_number']);
                                                    $bank_info = !empty($b['bank_name']) ? ' (' . htmlspecialchars($b['bank_name']) . ')' : '';
                                                    $star = $b['is_favorite'] ? '⭐ ' : '';
                                                    $selected = (isset($_GET['beneficiary']) && $_GET['beneficiary'] == $b['id']) ? 'selected' : '';
                                                ?>
                                                    <option value="<?php echo $b['id']; ?>" <?php echo $selected; ?>>
                                                        <?php echo $star . $display_name; ?> - <?php echo $display_account . $bank_info; ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                            <div class="form-text">
                                                <a href="beneficiaries.php" target="_blank">Manage your beneficiaries</a>
                                            </div>
                                            <!-- Add hidden input for beneficiary transfer method -->
                                            <input type="hidden" name="transferMethod" value="beneficiary" id="transferMethodBeneficiary" disabled>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="d-flex justify-content-between mt-4">
                                    <a href="transfer.php?step=1" class="btn btn-secondary">Back</a>
                                    <button type="submit" class="btn btn-primary">Next</button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            
            <!-- Step 3: Confirm -->
            <?php elseif ($current_step == 3): ?>
                <div class="wizard-step">
                    <h4 class="text-center">Please confirm the details</h4>
                    
                    <?php
                    // Get recipient details
                    $recipientName = '';
                    $recipientAccount = '';
                    $recipientId = null;
                    
                    if ($_SESSION['transfer_data']['transferMethod'] === 'account') {
                        $accountNumber = $_SESSION['transfer_data']['accountNumber'];
                        $stmt = $db->prepare("SELECT id, first_name, last_name, account_number FROM users WHERE account_number = ? AND id != ? AND status = 'active'");
                        $stmt->execute([$accountNumber, $_SESSION['user_id']]);
                        $recipient = $stmt->fetch(PDO::FETCH_ASSOC);
                        
                        if ($recipient) {
                            $recipientName = $recipient['first_name'] . ' ' . $recipient['last_name'];
                            $recipientAccount = $recipient['account_number'];
                            $recipientId = $recipient['id'];
                        }
                    } elseif ($_SESSION['transfer_data']['transferMethod'] === 'beneficiary') {
                        $beneficiaryId = $_SESSION['transfer_data']['beneficiaryId'];
                        // Fixed query to correctly look up beneficiary by ID
                        $stmt = $db->prepare("
                            SELECT u.id, u.first_name, u.last_name, u.account_number 
                            FROM users u 
                            JOIN beneficiaries b ON u.id = b.recipient_id 
                            WHERE b.id = ? AND b.user_id = ?
                        ");
                        $stmt->execute([$beneficiaryId, $_SESSION['user_id']]);
                        $recipient = $stmt->fetch(PDO::FETCH_ASSOC);
                        
                        if ($recipient) {
                            $recipientName = $recipient['first_name'] . ' ' . $recipient['last_name'];
                            $recipientAccount = $recipient['account_number'];
                            $recipientId = $recipient['id'];
                        }
                    }
                    
                    // Fetch user's balance and currency
                    $stmt = $db->prepare("
                        SELECT ab.balance, u.currency 
                        FROM account_balances ab
                        JOIN users u ON ab.user_id = u.id
                        WHERE ab.user_id = ?
                    ");
                    $stmt->execute([$_SESSION['user_id']]);
                    $userInfo = $stmt->fetch(PDO::FETCH_ASSOC);
                    ?>
                    
                    <form method="POST" action="process_transfer.php">
                        <!-- Transfer data -->
                        <input type="hidden" name="amount" value="<?php echo htmlspecialchars($_SESSION['transfer_data']['amount']); ?>">
                        <input type="hidden" name="description" value="<?php echo htmlspecialchars($_SESSION['transfer_data']['description']); ?>">
                        <input type="hidden" name="transferMethod" value="<?php echo htmlspecialchars($_SESSION['transfer_data']['transferMethod']); ?>">
                        
                        <?php if ($_SESSION['transfer_data']['transferMethod'] === 'account'): ?>
                            <input type="hidden" name="accountNumber" value="<?php echo htmlspecialchars($_SESSION['transfer_data']['accountNumber']); ?>">
                        <?php else: ?>
                            <input type="hidden" name="beneficiaryId" value="<?php echo htmlspecialchars($_SESSION['transfer_data']['beneficiaryId']); ?>">
                        <?php endif; ?>
                        
                        <div class="row justify-content-center">
                            <div class="col-md-8">
                                <?php if ($recipientId): ?>
                                    <div class="alert alert-info text-center">
                                        <p class="mb-1">You are sending</p>
                                        <h2 class="fw-bold"><?php echo htmlspecialchars($userInfo['currency']); ?> <?php echo number_format($_SESSION['transfer_data']['amount'], 2); ?></h2>
                                        <p class="mb-1 mt-3">To</p>
                                        <h5 class="fw-bold"><?php echo htmlspecialchars($recipientName); ?></h5>
                                        <p class="text-muted">Account: <?php echo htmlspecialchars($recipientAccount); ?></p>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">Enter your 4-digit PIN to authorize</label>
                                        <input type="password" class="form-control form-control-lg text-center" name="pin" maxlength="4" required style="letter-spacing: 1em;">
                                    </div>
                                    
                                    <?php if ($_SESSION['transfer_data']['transferMethod'] === 'account'): ?>
                                        <div class="mb-3 form-check">
                                            <input type="checkbox" class="form-check-input" id="saveBeneficiary" name="saveBeneficiary" value="1">
                                            <label class="form-check-label" for="saveBeneficiary">Save as beneficiary</label>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <div class="d-flex justify-content-between mt-4">
                                        <a href="transfer.php?step=2" class="btn btn-secondary">Back</a>
                                        <button type="submit" class="btn btn-success btn-lg">Confirm & Send</button>
                                    </div>
                                <?php else: ?>
                                    <div class="alert alert-danger">
                                        <p>Could not verify recipient details. Please go back and try again.</p>
                                    </div>
                                    <div class="d-flex justify-content-between mt-4">
                                        <a href="transfer.php?step=2" class="btn btn-secondary">Back</a>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </form>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

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

<script>
document.addEventListener('DOMContentLoaded', function() {
    console.log('Transfer wizard script loaded');
    
    // Tab switching for Step 2
    const accountTab = document.getElementById('account-tab');
    const beneficiaryTab = document.getElementById('beneficiary-tab');
    const transferMethodAccount = document.getElementById('transferMethodAccount');
    const transferMethodBeneficiary = document.getElementById('transferMethodBeneficiary');
    
    if (accountTab && beneficiaryTab && transferMethodAccount && transferMethodBeneficiary) {
        // Set initial state based on active tab
        if (document.querySelector('#account-pane.show.active')) {
            transferMethodAccount.disabled = false;
            transferMethodBeneficiary.disabled = true;
        } else if (document.querySelector('#beneficiary-pane.show.active')) {
            transferMethodAccount.disabled = true;
            transferMethodBeneficiary.disabled = false;
        }
        
        accountTab.addEventListener('click', function() {
            transferMethodAccount.disabled = false;
            transferMethodBeneficiary.disabled = true;
        });
        
        beneficiaryTab.addEventListener('click', function() {
            transferMethodAccount.disabled = true;
            transferMethodBeneficiary.disabled = false;
        });
    }
});
</script>
