<?php
require_once 'includes/auth_check.php';
$page = 'users';
require_once '../config/database.php';

// --- Helper function to check if a table exists ---
function tableExists($db, $tableName) {
    try {
        $result = $db->query("SELECT 1 FROM `$tableName` LIMIT 1");
        return $result !== false;
    } catch (Exception $e) {
        return false;
    }
}

// --- Get User ID ---
$user_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$user_id) {
    $_SESSION['error_message'] = "No user ID provided.";
    header('Location: manage_users.php');
    exit;
}

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

// --- Initialize all variables to prevent errors ---
$user = null;
$balances = [];
$transactions = [];
$kin = [];
$documents = [];
$financialProfile = [];
$securityQuestions = [];
$pageError = null;

// --- 1. Fetch CRITICAL User Data ---
try {
    $stmt = $db->prepare("SELECT * FROM users WHERE id = :id");
    $stmt->execute([':id' => $user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        $_SESSION['error_message'] = "User with ID $user_id not found.";
        header('Location: manage_users.php');
        exit;
    }
} catch (PDOException $e) {
    $pageError = "A critical database error occurred while fetching user data. Please check the logs.";
    error_log("View User CRITICAL Error: " . $e->getMessage());
}

// --- 2. Fetch NON-CRITICAL Data (page will still load if these fail) ---
if ($user) {
    // Fetch account balances
    if (tableExists($db, 'account_balances')) {
        try {
            $balance_stmt = $db->prepare("SELECT * FROM account_balances WHERE user_id = :id ORDER BY currency ASC");
            $balance_stmt->execute([':id' => $user_id]);
            $balances = $balance_stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) { error_log("View User (Balances) Error: " . $e->getMessage()); }
    }

    // Fetch next of kin
    if (tableExists($db, 'next_of_kin')) {
        try {
            $kin_stmt = $db->prepare("SELECT * FROM next_of_kin WHERE user_id = :id");
            $kin_stmt->execute([':id' => $user_id]);
            $kin = $kin_stmt->fetch(PDO::FETCH_ASSOC);
        } catch (PDOException $e) { error_log("View User (Next of Kin) Error: " . $e->getMessage()); }
    }
    
    // Fetch transactions
    if (tableExists($db, 'transactions')) {
        try {
            $trans_stmt = $db->prepare("SELECT * FROM transactions WHERE user_id = :id ORDER BY created_at DESC LIMIT 10");
            $trans_stmt->execute([':id' => $user_id]);
            $transactions = $trans_stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) { error_log("View User (Transactions) Error: " . $e->getMessage()); }
    }
    
    // Fetch user documents
    if (tableExists($db, 'user_documents')) {
        try {
            $doc_stmt = $db->prepare("SELECT * FROM user_documents WHERE user_id = :id");
            $doc_stmt->execute([':id' => $user_id]);
            $documents = $doc_stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) { error_log("View User (Documents) Error: " . $e->getMessage()); }
    }
    
    // Fetch financial profile
    if (tableExists($db, 'user_financial_profile')) {
        try {
            $fin_stmt = $db->prepare("SELECT * FROM user_financial_profile WHERE user_id = :id");
            $fin_stmt->execute([':id' => $user_id]);
            $financialProfileData = $fin_stmt->fetchAll(PDO::FETCH_ASSOC);
            
            // Convert to associative array for easier access
            foreach ($financialProfileData as $item) {
                $financialProfile[$item['field_name']] = $item['field_value'];
            }
        } catch (PDOException $e) { error_log("View User (Financial Profile) Error: " . $e->getMessage()); }
    }
    
    // Fetch security questions
    if (tableExists($db, 'security_questions')) {
        try {
            $sec_stmt = $db->prepare("SELECT * FROM security_questions WHERE user_id = :id");
            $sec_stmt->execute([':id' => $user_id]);
            $securityQuestions = $sec_stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) { error_log("View User (Security Questions) Error: " . $e->getMessage()); }
    }
    
    // Fetch user's cards
    $cards = [];
    if (tableExists($db, 'cards')) {
        try {
            $cards_stmt = $db->prepare("SELECT * FROM cards WHERE user_id = :id ORDER BY created_at DESC");
            $cards_stmt->execute([':id' => $user_id]);
            $cards = $cards_stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) { error_log("View User (Cards) Error: " . $e->getMessage()); }
    }

    // Fetch user's external cards
    $external_cards = [];
    if (tableExists($db, 'external_cards')) {
        try {
            $ext_cards_stmt = $db->prepare("SELECT * FROM external_cards WHERE user_id = :id ORDER BY created_at DESC");
            $ext_cards_stmt->execute([':id' => $user_id]);
            $external_cards = $ext_cards_stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) { error_log("View User (External Cards) Error: " . $e->getMessage()); }
    }
}

// Helper function to format card number
function formatCardNumber($number) {
    return implode(' ', str_split($number, 4));
}

include 'includes/header.php';
?>

<div class="content-wrapper">
    <div class="container-fluid">
        <!-- Page Header -->
        <div class="page-header d-flex justify-content-between align-items-center">
            <div>
                <h1 class="page-header-title">User Profile</h1>
                <?php if ($user): ?>
                    <p class="text-muted">ID: <?php echo $user['id']; ?> | Registered: <?php echo date('M j, Y', strtotime($user['created_at'] ?? 'now')); ?></p>
                <?php endif; ?>
            </div>
            <div class="d-flex">
                <a href="manage_users.php" class="btn btn-sm btn-secondary me-2">
                    <i class="bx bx-arrow-back"></i> Back to Users
                </a>
                <a href="edit_user.php?id=<?php echo $user_id; ?>" class="btn btn-sm btn-warning me-2">
                    <i class="bx bx-edit"></i> Edit User
                </a>
                <div class="btn-group">
                    <button type="button" class="btn btn-sm btn-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">Actions</button>
                    <ul class="dropdown-menu dropdown-menu-end">
                        <li><a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#adjustBalanceModal">
                            <i class="bx bx-money"></i> Adjust Balance
                        </a></li>
                        <li><a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#resetPasswordModal">
                            <i class="bx bx-lock-open"></i> Reset Password
                        </a></li>
                        <li><hr class="dropdown-divider"></li>
                        <?php if (($user['status'] ?? '') === 'active'): ?>
                            <li><a class="dropdown-item text-warning" href="#" data-bs-toggle="modal" data-bs-target="#suspendUserModal">
                                <i class="bx bx-pause-circle"></i> Suspend User
                            </a></li>
                        <?php else: ?>
                            <li><a class="dropdown-item text-success" href="#" data-bs-toggle="modal" data-bs-target="#activateUserModal">
                                <i class="bx bx-play-circle"></i> Activate User
                            </a></li>
                        <?php endif; ?>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item text-danger" href="#" data-bs-toggle="modal" data-bs-target="#deleteUserModal">
                            <i class="bx bx-trash"></i> Delete User
                        </a></li>
                    </ul>
                </div>
            </div>
        </div>

        <!-- Success/Error Messages -->
        <?php if (isset($_SESSION['success_message'])): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="bx bx-check-circle me-2"></i>
                <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <?php if (isset($_SESSION['error_message'])): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="bx bx-error-circle me-2"></i>
                <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <!-- Display Critical Error if it occurred -->
        <?php if ($pageError): ?>
            <div class="alert alert-danger"><?php echo $pageError; ?></div>
        <?php elseif ($user): ?>
        
        <!-- Main Content Grid -->
        <div class="row">
            <!-- Left Column -->
            <div class="col-lg-4">
                <!-- Profile Card -->
                <div class="card mb-4">
                    <div class="card-body text-center">
                        <div class="position-relative d-inline-block mb-3">
                            <img src="../<?php echo !empty($user['profile_picture']) ? 'uploads/profiles/' . htmlspecialchars($user['profile_picture']) : 'assets/images/default-avatar.png'; ?>" 
                                 alt="Profile Picture" class="rounded-circle img-fluid" style="width: 150px; height: 150px; object-fit: cover;">
                            <span class="position-absolute bottom-0 end-0 badge rounded-pill bg-<?php echo ($user['status'] == 'active' ? 'success' : 'warning'); ?>">
                                <?php echo ucfirst($user['status'] ?? 'N/A'); ?>
                            </span>
                        </div>
                        <h4 class="mb-1"><?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?></h4>
                        <p class="text-muted mb-1"><?php echo htmlspecialchars($user['email']); ?></p>
                        <p class="text-muted mb-3">
                            <i class="bx bx-map"></i> <?php echo htmlspecialchars($user['country'] ?? 'N/A'); ?>
                        </p>
                        <div class="d-flex justify-content-center gap-2">
                            <a href="mailto:<?php echo htmlspecialchars($user['email']); ?>" class="btn btn-sm btn-outline-primary">
                                <i class="bx bx-envelope"></i> Email
                            </a>
                            <?php if (!empty($user['phone'])): ?>
                            <a href="tel:<?php echo htmlspecialchars($user['phone']); ?>" class="btn btn-sm btn-outline-primary">
                                <i class="bx bx-phone"></i> Call
                            </a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Account Balances Card -->
                <div class="card mb-4">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="card-title mb-0"><i class="bx bx-wallet text-primary me-2"></i>Account Balances</h5>
                        <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#adjustBalanceModal">
                            <i class="bx bx-plus"></i> Adjust
                        </button>
                    </div>
                    <div class="card-body p-0">
                        <ul class="list-group list-group-flush">
                            <?php if (empty($balances)): ?>
                                <li class="list-group-item text-muted">No balance records found.</li>
                            <?php else: ?>
                                <?php foreach ($balances as $balance): ?>
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        <div>
                                            <i class="bx bx-dollar-circle me-2 text-primary"></i>
                                            <strong><?php echo htmlspecialchars($balance['currency']); ?></strong>
                                        </div>
                                        <span class="badge bg-light text-dark fs-6">
                                            <?php echo number_format($balance['balance'], ($balance['currency'] === 'BTC' ? 8 : 2)); ?>
                                        </span>
                                    </li>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </ul>
                    </div>
                </div>

                <!-- Account Information Card -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="card-title mb-0"><i class="bx bx-credit-card text-primary me-2"></i>Account Information</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="small text-muted">Account Number</label>
                            <div class="d-flex align-items-center">
                                <h6 class="mb-0 me-2"><?php echo htmlspecialchars($user['account_number'] ?? 'N/A'); ?></h6>
                                <button class="btn btn-sm btn-outline-secondary" onclick="copyToClipboard('<?php echo htmlspecialchars($user['account_number'] ?? ''); ?>')">
                                    <i class="bx bx-copy"></i>
                                </button>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="small text-muted">Account Type</label>
                            <h6 class="mb-0"><?php echo ucfirst(htmlspecialchars($user['account_type'] ?? 'N/A')); ?></h6>
                        </div>
                        <div class="mb-3">
                            <label class="small text-muted">Currency</label>
                            <h6 class="mb-0"><?php echo htmlspecialchars($user['currency'] ?? 'N/A'); ?></h6>
                        </div>
                        <div>
                            <label class="small text-muted">Created On</label>
                            <h6 class="mb-0"><?php echo date('F j, Y', strtotime($user['created_at'] ?? 'now')); ?></h6>
                        </div>
                    </div>
                </div>

                <!-- Documents Card -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="card-title mb-0"><i class="bx bx-file text-primary me-2"></i>Documents</h5>
                    </div>
                    <div class="card-body p-0">
                        <ul class="list-group list-group-flush">
                            <?php if (empty($documents)): ?>
                                <li class="list-group-item text-muted">No documents found.</li>
                            <?php else: ?>
                                <?php foreach ($documents as $doc): ?>
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        <div>
                                            <?php 
                                            $icon = 'bx-file';
                                            $docType = $doc['document_type'] ?? '';
                                            
                                            if (strpos($docType, 'id') !== false) {
                                                $icon = 'bx-id-card';
                                            } elseif (strpos($docType, 'utility') !== false) {
                                                $icon = 'bx-receipt';
                                            }
                                            ?>
                                            <i class="bx <?php echo $icon; ?> me-2"></i>
                                            <span><?php echo ucwords(str_replace('_', ' ', $doc['document_type'] ?? 'Document')); ?></span>
                                        </div>
                                        <div>
                                            <span class="badge bg-<?php 
                                                $status = $doc['status'] ?? 'pending';
                                                echo $status === 'approved' ? 'success' : ($status === 'rejected' ? 'danger' : 'warning');
                                            ?>">
                                                <?php echo ucfirst($doc['status'] ?? 'Pending'); ?>
                                            </span>
                                            <!-- FIX: Updated document path to point to root uploads folder -->
                                            <a href="#" class="btn btn-sm btn-outline-primary ms-2" 
                                               onclick="viewDocument('../uploads/documents/<?php echo basename($doc['file_path'] ?? ''); ?>')">
                                                <i class="bx bx-show"></i>
                                            </a>
                                        </div>
                                    </li>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </ul>
                    </div>
                </div>
            </div>

            <!-- Right Column -->
            <div class="col-lg-8">
                <!-- Tabs Navigation -->
                <ul class="nav nav-tabs mb-4" id="userProfileTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="personal-tab" data-bs-toggle="tab" data-bs-target="#personal" type="button" role="tab" aria-controls="personal" aria-selected="true">
                            <i class="bx bx-user me-1"></i> Personal
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="financial-tab" data-bs-toggle="tab" data-bs-target="#financial" type="button" role="tab" aria-controls="financial" aria-selected="false">
                            <i class="bx bx-dollar-circle me-1"></i> Financial
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="security-tab" data-bs-toggle="tab" data-bs-target="#security" type="button" role="tab" aria-controls="security" aria-selected="false">
                            <i class="bx bx-lock me-1"></i> Security
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="transactions-tab" data-bs-toggle="tab" data-bs-target="#transactions" type="button" role="tab" aria-controls="transactions" aria-selected="false">
                            <i class="bx bx-transfer me-1"></i> Transactions
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="cards-tab" data-bs-toggle="tab" data-bs-target="#cards" type="button" role="tab" aria-controls="cards" aria-selected="false">
                            <i class="bx bx-credit-card me-1"></i> Cards
                        </button>
                    </li>
                </ul>

                <!-- Tabs Content -->
                <div class="tab-content" id="userProfileTabsContent">
                    <!-- Personal Information Tab -->
                    <div class="tab-pane fade show active" id="personal" role="tabpanel" aria-labelledby="personal-tab">
                        <!-- Personal Information Card -->
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5 class="card-title mb-0"><i class="bx bx-user-circle text-primary me-2"></i>Personal Information</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="small text-muted">First Name</label>
                                        <p class="mb-0"><?php echo htmlspecialchars($user['first_name'] ?? 'N/A'); ?></p>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="small text-muted">Last Name</label>
                                        <p class="mb-0"><?php echo htmlspecialchars($user['last_name'] ?? 'N/A'); ?></p>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="small text-muted">Email</label>
                                        <p class="mb-0"><?php echo htmlspecialchars($user['email'] ?? 'N/A'); ?></p>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="small text-muted">Phone</label>
                                        <p class="mb-0"><?php echo htmlspecialchars($user['phone'] ?? 'N/A'); ?></p>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="small text-muted">Date of Birth</label>
                                        <p class="mb-0"><?php echo date('F j, Y', strtotime($user['date_of_birth'] ?? 'now')); ?></p>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="small text-muted">Gender</label>
                                        <p class="mb-0"><?php echo ucfirst(htmlspecialchars($user['gender'] ?? 'N/A')); ?></p>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="small text-muted">Social Security Number</label>
                                        <p class="mb-0"><?php echo htmlspecialchars($user['ssn'] ?? 'N/A'); ?></p>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="small text-muted">Mother's Maiden Name</label>
                                        <p class="mb-0"><?php echo htmlspecialchars($user['mothers_maiden_name'] ?? 'N/A'); ?></p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Address Information Card -->
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5 class="card-title mb-0"><i class="bx bx-map text-primary me-2"></i>Address Information</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-12 mb-3">
                                        <label class="small text-muted">Street Address</label>
                                        <p class="mb-0"><?php echo htmlspecialchars($user['address'] ?? 'N/A'); ?></p>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="small text-muted">City</label>
                                        <p class="mb-0"><?php echo htmlspecialchars($user['city'] ?? 'N/A'); ?></p>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="small text-muted">State/Province</label>
                                        <p class="mb-0"><?php echo htmlspecialchars($user['state'] ?? 'N/A'); ?></p>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="small text-muted">Zip/Postal Code</label>
                                        <p class="mb-0"><?php echo htmlspecialchars($user['zip_code'] ?? 'N/A'); ?></p>
                                    </div>
                                    <div class="col-md-12">
                                        <label class="small text-muted">Country</label>
                                        <p class="mb-0"><?php echo htmlspecialchars($user['country'] ?? 'N/A'); ?></p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Employment Information Card -->
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5 class="card-title mb-0"><i class="bx bx-briefcase text-primary me-2"></i>Employment Information</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="small text-muted">Employment Status</label>
                                        <!-- FIX: Properly display employment_status from users table -->
                                        <p class="mb-0"><?php echo ucfirst(htmlspecialchars($user['employment_status'] ?? 'N/A')); ?></p>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="small text-muted">Income Source</label>
                                        <!-- FIX: Properly display income_source from users table -->
                                        <p class="mb-0"><?php echo ucfirst(htmlspecialchars($user['income_source'] ?? 'N/A')); ?></p>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="small text-muted">Occupation</label>
                                        <!-- FIX: Properly display occupation from users table -->
                                        <p class="mb-0"><?php echo htmlspecialchars($user['occupation'] ?? 'N/A'); ?></p>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="small text-muted">Employer</label>
                                        <!-- FIX: Properly display employer from users table -->
                                        <p class="mb-0"><?php echo htmlspecialchars($user['employer'] ?? 'N/A'); ?></p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Next of Kin Card -->
                        <?php if (!empty($kin)): ?>
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5 class="card-title mb-0"><i class="bx bx-user-pin text-primary me-2"></i>Next of Kin</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="small text-muted">Full Name</label>
                                        <p class="mb-0"><?php echo htmlspecialchars($kin['full_name'] ?? 'N/A'); ?></p>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="small text-muted">Relationship</label>
                                        <p class="mb-0"><?php echo ucfirst(htmlspecialchars($kin['relationship'] ?? 'N/A')); ?></p>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="small text-muted">Email</label>
                                        <p class="mb-0"><?php echo htmlspecialchars($kin['email'] ?? 'N/A'); ?></p>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="small text-muted">Phone</label>
                                        <p class="mb-0"><?php echo htmlspecialchars($kin['phone'] ?? 'N/A'); ?></p>
                                    </div>
                                    <div class="col-md-12">
                                        <label class="small text-muted">Address</label>
                                        <p class="mb-0"><?php echo htmlspecialchars($kin['address'] ?? 'N/A'); ?></p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>

                    <!-- Financial Information Tab -->
                    <div class="tab-pane fade" id="financial" role="tabpanel" aria-labelledby="financial-tab">
                        <!-- Financial Profile Card -->
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5 class="card-title mb-0"><i class="bx bx-dollar-circle text-primary me-2"></i>Financial Profile</h5>
                            </div>
                            <div class="card-body">
                                <!-- Other Bank Accounts -->
                                <div class="mb-4">
                                    <h6 class="mb-3">Other Bank Accounts</h6>
                                                                        <?php if (isset($financialProfile['other_bank_accounts']) && !empty($financialProfile['other_bank_accounts'])): ?>
                                        <div class="alert alert-info mb-0">
                                            <p class="mb-0"><?php echo nl2br(htmlspecialchars($financialProfile['other_bank_accounts'])); ?></p>
                                        </div>
                                    <?php else: ?>
                                        <p class="text-muted mb-0">No other bank accounts reported.</p>
                                    <?php endif; ?>
                                </div>

                                <!-- Credit Cards -->
                                <div class="mb-4">
                                    <h6 class="mb-3">Credit Cards</h6>
                                    <?php if (isset($financialProfile['other_credit_cards']) && !empty($financialProfile['other_credit_cards'])): ?>
                                        <div class="mb-2">
                                            <label class="small text-muted">Number of Credit Cards</label>
                                            <p><?php echo htmlspecialchars($financialProfile['credit_card_count'] ?? 'N/A'); ?></p>
                                        </div>
                                        <div class="alert alert-info mb-0">
                                            <p class="mb-0"><?php echo nl2br(htmlspecialchars($financialProfile['other_credit_cards'])); ?></p>
                                        </div>
                                    <?php else: ?>
                                        <p class="text-muted mb-0">No credit cards reported.</p>
                                    <?php endif; ?>
                                </div>

                                <!-- Investment Accounts -->
                                <div class="mb-4">
                                    <h6 class="mb-3">Investment Accounts</h6>
                                    <?php if (isset($financialProfile['investment_accounts']) && !empty($financialProfile['investment_accounts'])): ?>
                                        <div class="alert alert-info mb-0">
                                            <p class="mb-0"><?php echo nl2br(htmlspecialchars($financialProfile['investment_accounts'])); ?></p>
                                        </div>
                                    <?php else: ?>
                                        <p class="text-muted mb-0">No investment accounts reported.</p>
                                    <?php endif; ?>
                                </div>

                                <!-- 401(k) Accounts -->
                                <div class="mb-4">
                                    <h6 class="mb-3">401(k) Accounts</h6>
                                    <?php if (isset($financialProfile['401k_accounts']) && !empty($financialProfile['401k_accounts'])): ?>
                                        <div class="alert alert-info mb-0">
                                            <p class="mb-0"><?php echo nl2br(htmlspecialchars($financialProfile['401k_accounts'])); ?></p>
                                        </div>
                                    <?php else: ?>
                                        <p class="text-muted mb-0">No 401(k) accounts reported.</p>
                                    <?php endif; ?>
                                </div>

                                <!-- Home Equity -->
                                <div class="mb-4">
                                    <h6 class="mb-3">Home Equity Line of Credit</h6>
                                    <?php if (isset($financialProfile['home_equity_accounts']) && !empty($financialProfile['home_equity_accounts'])): ?>
                                        <div class="alert alert-info mb-0">
                                            <p class="mb-0"><?php echo nl2br(htmlspecialchars($financialProfile['home_equity_accounts'])); ?></p>
                                        </div>
                                    <?php else: ?>
                                        <p class="text-muted mb-0">No home equity line of credit reported.</p>
                                    <?php endif; ?>
                                </div>

                                <!-- Business Accounts -->
                                <div class="mb-4">
                                    <h6 class="mb-3">Business Accounts</h6>
                                    <?php if (isset($financialProfile['business_accounts']) && !empty($financialProfile['business_accounts'])): ?>
                                        <div class="alert alert-info mb-0">
                                            <p class="mb-0"><?php echo nl2br(htmlspecialchars($financialProfile['business_accounts'])); ?></p>
                                        </div>
                                    <?php else: ?>
                                        <p class="text-muted mb-0">No business accounts reported.</p>
                                    <?php endif; ?>
                                </div>

                                <!-- Mortgage Accounts -->
                                <div>
                                    <h6 class="mb-3">Mortgage Accounts</h6>
                                    <?php if (isset($financialProfile['mortgage_accounts']) && !empty($financialProfile['mortgage_accounts'])): ?>
                                        <div class="alert alert-info mb-0">
                                            <p class="mb-0"><?php echo nl2br(htmlspecialchars($financialProfile['mortgage_accounts'])); ?></p>
                                        </div>
                                    <?php else: ?>
                                        <p class="text-muted mb-0">No mortgage accounts reported.</p>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <!-- Account Preferences Card -->
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5 class="card-title mb-0"><i class="bx bx-cog text-primary me-2"></i>Account Preferences</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="small text-muted">Debit Card Requested</label>
                                        <p class="mb-0">
                                            <?php 
                                            $debitCard = $user['request_debit_card'] ?? '';
                                            echo $debitCard === 'yes' ? 
                                                '<span class="badge bg-success">Yes</span>' : 
                                                '<span class="badge bg-secondary">No</span>'; 
                                            ?>
                                        </p>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="small text-muted">Online Banking</label>
                                        <p class="mb-0">
                                            <?php 
                                            $onlineBanking = $user['online_banking'] ?? '';
                                            echo $onlineBanking === 'yes' ? 
                                                '<span class="badge bg-success">Enabled</span>' : 
                                                '<span class="badge bg-secondary">Disabled</span>'; 
                                            ?>
                                        </p>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="small text-muted">Initial Deposit Range</label>
                                        <!-- FIX: Properly display initial_deposit from users table -->
                                        <p class="mb-0"><?php echo htmlspecialchars($user['initial_deposit'] ?? 'N/A'); ?></p>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="small text-muted">Two-Factor Authentication</label>
                                        <p class="mb-0">
                                            <?php 
                                            $twoFactor = $user['two_factor_enabled'] ?? 0;
                                            echo $twoFactor ? 
                                                '<span class="badge bg-success">Enabled</span>' : 
                                                '<span class="badge bg-secondary">Disabled</span>'; 
                                            ?>
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Security Tab -->
                    <div class="tab-pane fade" id="security" role="tabpanel" aria-labelledby="security-tab">
                        <!-- Account Security Card -->
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5 class="card-title mb-0"><i class="bx bx-lock-alt text-primary me-2"></i>Account Security</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="small text-muted">Username</label>
                                        <p class="mb-0"><?php echo htmlspecialchars($user['username'] ?? 'N/A'); ?></p>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="small text-muted">Password</label>
                                        <div class="d-flex align-items-center">
                                            <p class="mb-0">••••••••</p>
                                            <button class="btn btn-sm btn-outline-primary ms-2" data-bs-toggle="modal" data-bs-target="#resetPasswordModal">
                                                <i class="bx bx-reset"></i> Reset
                                            </button>
                                        </div>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="small text-muted">PIN</label>
                                        <p class="mb-0">••••</p>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="small text-muted">Two-Factor Authentication</label>
                                        <p class="mb-0">
                                            <?php 
                                            $twoFactor = $user['two_factor_enabled'] ?? 0;
                                            echo $twoFactor ? 
                                                '<span class="badge bg-success">Enabled</span>' : 
                                                '<span class="badge bg-secondary">Disabled</span>'; 
                                            ?>
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Security Questions Card -->
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5 class="card-title mb-0"><i class="bx bx-question-mark text-primary me-2"></i>Security Questions</h5>
                            </div>
                            <div class="card-body">
                                <?php if (empty($securityQuestions)): ?>
                                    <p class="text-muted">No security questions set up.</p>
                                <?php else: ?>
                                    <?php foreach ($securityQuestions as $index => $question): ?>
                                        <div class="mb-3 <?php echo ($index === count($securityQuestions) - 1) ? 'mb-0' : ''; ?>">
                                            <label class="small text-muted">Question <?php echo $index + 1; ?></label>
                                            <p class="mb-0">
                                                <?php 
                                                $questionKey = $question['question_key'] ?? '';
                                                $questionText = '';
                                                
                                                switch ($questionKey) {
                                                    case 'first_pet':
                                                        $questionText = 'What was the name of your first pet?';
                                                        break;
                                                    case 'birth_city':
                                                        $questionText = 'In what city were you born?';
                                                        break;

                                                    case 'mother_maiden':
                                                        $questionText = 'What is your mother\'s maiden name?';
                                                        break;
                                                    case 'high_school':
                                                        $questionText = 'What high school did you attend?';
                                                        break;
                                                    case 'first_car':
                                                        $questionText = 'What was the make of your first car?';
                                                        break;
                                                    case 'favorite_teacher':
                                                        $questionText = 'Who was your favorite teacher?';
                                                        break;
                                                    case 'first_job':
                                                        $questionText = 'What was your first job?';
                                                        break;
                                                    case 'childhood_friend':
                                                        $questionText = 'What is the name of your childhood best friend?';
                                                        break;
                                                    case 'favorite_food':
                                                        $questionText = 'What is your favorite food?';
                                                        break;
                                                    case 'childhood_hero':
                                                        $questionText = 'Who was your childhood hero?';
                                                        break;
                                                    default:
                                                        $questionText = ucwords(str_replace('_', ' ', $questionKey));
                                                }
                                                
                                                echo htmlspecialchars($questionText);
                                                ?>
                                            </p>
                                            <!-- FIX: Show the actual answer instead of just "Answer Set" -->
                                            <div class="mt-1">
                                                <label class="small text-muted">Answer</label>
                                                <p class="mb-0">
                                                    <?php echo htmlspecialchars($question['answer'] ?? 'N/A'); ?>
                                                </p>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Login History Card -->
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="card-title mb-0"><i class="bx bx-history text-primary me-2"></i>Login History</h5>
                                <a href="user_login_history.php?id=<?php echo $user_id; ?>" class="btn btn-sm btn-outline-primary">
                                    View All
                                </a>
                            </div>
                            <div class="card-body p-0">
                                <div class="table-responsive">
                                    <table class="table table-hover mb-0">
                                        <thead>
                                            <tr>
                                                <th>Date & Time</th>
                                                <th>IP Address</th>
                                                <th>Device</th>
                                                <th>Status</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            // Fetch login history if the table exists
                                            $loginHistory = [];
                                            if (tableExists($db, 'login_history')) {
                                                try {
                                                    $login_stmt = $db->prepare("SELECT * FROM login_history WHERE user_id = :id ORDER BY login_time DESC LIMIT 5");
                                                    $login_stmt->execute([':id' => $user_id]);
                                                    $loginHistory = $login_stmt->fetchAll(PDO::FETCH_ASSOC);
                                                } catch (PDOException $e) { 
                                                    error_log("View User (Login History) Error: " . $e->getMessage()); 
                                                }
                                            }
                                            
                                            if (empty($loginHistory)):
                                            ?>
                                                <tr>
                                                    <td colspan="4" class="text-center text-muted">No login history available.</td>
                                                </tr>
                                            <?php else: ?>
                                                <?php foreach ($loginHistory as $login): ?>
                                                    <tr>
                                                        <td><?php echo date('Y-m-d H:i:s', strtotime($login['login_time'] ?? 'now')); ?></td>
                                                        <td><?php echo htmlspecialchars($login['ip_address'] ?? 'N/A'); ?></td>
                                                        <td><?php echo htmlspecialchars($login['device_info'] ?? $login['user_agent'] ?? 'N/A'); ?></td>
                                                        <td>
                                                            <span class="badge bg-<?php echo ($login['status'] ?? '') === 'success' ? 'success' : 'danger'; ?>">
                                                                <?php echo ucfirst($login['status'] ?? 'N/A'); ?>
                                                            </span>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Transactions Tab -->
                    <div class="tab-pane fade" id="transactions" role="tabpanel" aria-labelledby="transactions-tab">
                        <!-- Transactions Card -->
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="card-title mb-0"><i class="bx bx-transfer text-primary me-2"></i>Recent Transactions</h5>
                                <a href="user_transactions.php?id=<?php echo $user_id; ?>" class="btn btn-sm btn-outline-primary">
                                    View All
                                </a>
                            </div>
                            <div class="card-body p-0">
                                <div class="table-responsive">
                                    <table class="table table-hover mb-0">
                                        <thead>
                                            <tr>
                                                <th>Date & Time</th>
                                                <th>Description</th>
                                                <th>Type</th>
                                                <th>Amount</th>
                                                <th>Status</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if (empty($transactions)): ?>
                                                <tr>
                                                    <td colspan="5" class="text-center text-muted">No transactions found.</td>
                                                </tr>
                                            <?php else: ?>
                                                <?php foreach ($transactions as $tx): ?>
                                                    <tr>
                                                        <td><?php echo date('Y-m-d H:i', strtotime($tx['created_at'])); ?></td>
                                                        <td><?php echo htmlspecialchars($tx['description']); ?></td>
                                                        <td>
                                                            <span class="badge bg-<?php echo $tx['type'] == 'credit' ? 'success' : 'danger'; ?>">
                                                                <?php echo ucfirst($tx['type']); ?>
                                                            </span>
                                                        </td>
                                                        <td class="fw-bold <?php echo $tx['type'] == 'credit' ? 'text-success' : 'text-danger'; ?>">
                                                            <?php echo htmlspecialchars($tx['currency']) . ' ' . number_format($tx['amount'], 2); ?>
                                                        </td>
                                                        <td>
                                                            <span class="badge bg-<?php echo $tx['status'] == 'completed' ? 'success' : 'warning'; ?>">
                                                                <?php echo ucfirst($tx['status']); ?>
                                                            </span>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <!-- Add Transaction Card -->
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0"><i class="bx bx-plus text-primary me-2"></i>Add Transaction</h5>
                            </div>
                            <div class="card-body">
                                <form action="user_actions.php" method="post">
                                    <input type="hidden" name="action" value="add_transaction">
                                    <input type="hidden" name="user_id" value="<?php echo $user_id; ?>">
                                    
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="transaction_type" class="form-label">Transaction Type</label>
                                            <select class="form-select" id="transaction_type" name="transaction_type" required>
                                                <option value="credit">Credit (Deposit)</option>
                                                <option value="debit">Debit (Withdrawal)</option>
                                            </select>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="transaction_currency" class="form-label">Currency</label>
                                            <select class="form-select" id="transaction_currency" name="transaction_currency" required>
                                                <?php if (empty($balances)): ?>
                                                    <option value="USD">USD</option>
                                                <?php else: ?>
                                                    <?php foreach ($balances as $b): ?>
                                                        <option value="<?php echo htmlspecialchars($b['currency']); ?>"><?php echo htmlspecialchars($b['currency']); ?></option>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="transaction_amount" class="form-label">Amount</label>
                                            <input type="number" class="form-control" id="transaction_amount" name="transaction_amount" step="0.01" required>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="transaction_status" class="form-label">Status</label>
                                            <select class="form-select" id="transaction_status" name="transaction_status" required>
                                                <option value="completed">Completed</option>
                                                <option value="pending">Pending</option>
                                                <option value="failed">Failed</option>
                                            </select>
                                        </div>
                                        <div class="col-12 mb-3">
                                            <label for="transaction_description" class="form-label">Description</label>
                                            <textarea class="form-control" id="transaction_description" name="transaction_description" rows="3" required></textarea>
                                        </div>
                                        <div class="col-12">
                                            <button type="submit" class="btn btn-primary">Add Transaction</button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <!-- Cards Tab -->
                    <div class="tab-pane fade" id="cards" role="tabpanel" aria-labelledby="cards-tab">
                        <!-- Bank Cards -->
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="card-title mb-0"><i class="bx bx-credit-card text-primary me-2"></i>Bank Cards</h5>
                                <a href="add_card.php?user_id=<?php echo $user_id; ?>" class="btn btn-sm btn-primary">
                                    <i class="bx bx-plus"></i> Add Card
                                </a>
                            </div>
                            <div class="card-body">
                                <?php if (empty($cards)): ?>
                                    <div class="text-center py-4">
                                        <i class="bx bx-credit-card" style="font-size: 3rem; color: #d1d5db;"></i>
                                        <p class="text-muted mt-3">No bank cards found for this user.</p>
                                    </div>
                                <?php else: ?>
                                    <div class="row">
                                        <?php foreach ($cards as $card): ?>
                                            <div class="col-md-6 mb-4">
                                                <div class="card h-100 border <?php echo $card['status'] === 'active' ? 'border-success' : 'border-warning'; ?>">
                                                    <div class="card-body">
                                                        <div class="d-flex justify-content-between align-items-center mb-3">
                                                            <h6 class="card-subtitle text-muted"><?php echo ucfirst($card['card_type']); ?> Card</h6>
                                                            <span class="badge bg-<?php echo $card['status'] === 'active' ? 'success' : 'warning'; ?>">
                                                                <?php echo ucfirst($card['status']); ?>
                                                            </span>
                                                        </div>
                                                        <h5 class="card-title">•••• •••• •••• <?php echo substr($card['card_number'], -4); ?></h5>
                                                        <div class="d-flex justify-content-between">
                                                            <div>
                                                                <small class="text-muted">Card Holder</small>
                                                                <p class="mb-0"><?php echo htmlspecialchars($card['card_holder_name']); ?></p>
                                                            </div>
                                                            <div>
                                                                <small class="text-muted">Expires</small>
                                                                <p class="mb-0"><?php echo sprintf('%02d', $card['expiry_month']) . '/' . substr($card['expiry_year'], -2); ?></p>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="card-footer bg-transparent">
                                                        <div class="d-flex justify-content-between">
                                                            <small class="text-muted">Created: <?php echo date('M j, Y', strtotime($card['created_at'])); ?></small>
                                                            <div>
                                                                <?php if ($card['status'] === 'active'): ?>
                                                                    <button class="btn btn-sm btn-outline-warning me-1" onclick="toggleCardStatus(<?php echo $card['id']; ?>, 'freeze')">
                                                                        <i class="bx bx-lock"></i> Freeze
                                                                    </button>
                                                                <?php else: ?>
                                                                    <button class="btn btn-sm btn-outline-success me-1" onclick="toggleCardStatus(<?php echo $card['id']; ?>, 'unfreeze')">
                                                                        <i class="bx bx-lock-open"></i> Unfreeze
                                                                    </button>
                                                                <?php endif; ?>
                                                                <button class="btn btn-sm btn-outline-danger" onclick="deleteCard(<?php echo $card['id']; ?>)">
                                                                    <i class="bx bx-trash"></i>
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- External Cards -->
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="card-title mb-0"><i class="bx bx-link text-primary me-2"></i>Linked External Cards</h5>
                                <button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#linkCardModal">
                                    <i class="bx bx-link"></i> Link Card
                                </button>
                            </div>
                            <div class="card-body">
                                <?php if (empty($external_cards)): ?>
                                    <div class="text-center py-4">
                                        <i class="bx bx-link-alt" style="font-size: 3rem; color: #d1d5db;"></i>
                                        <p class="text-muted mt-3">No external cards linked to this account.</p>
                                    </div>
                                <?php else: ?>
                                    <div class="row">
                                        <?php foreach ($external_cards as $ext_card): ?>
                                            <div class="col-md-6 mb-4">
                                                <div class="card h-100 border border-secondary bg-light">
                                                    <div class="card-body">
                                                        <div class="d-flex justify-content-between align-items-center mb-3">
                                                            <h6 class="card-subtitle text-muted"><?php echo ucfirst($ext_card['card_type']); ?> Card (External)</h6>
                                                            <span class="badge bg-<?php echo $ext_card['status'] === 'active' ? 'success' : 'warning'; ?>">
                                                                <?php echo ucfirst($ext_card['status']); ?>
                                                            </span>
                                                        </div>
                                                        <h5 class="card-title"><?php echo htmlspecialchars($ext_card['card_number']); ?></h5>
                                                        <div class="d-flex justify-content-between">
                                                            <div>
                                                                <small class="text-muted">Card Holder</small>
                                                                <p class="mb-0"><?php echo htmlspecialchars($ext_card['card_holder_name']); ?></p>
                                                            </div>
                                                            <div>
                                                                <small class="text-muted">Expires</small>
                                                                <p class="mb-0"><?php echo sprintf('%02d', $ext_card['expiry_month']) . '/' . substr($ext_card['expiry_year'], -2); ?></p>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="card-footer bg-transparent">
                                                        <div class="d-flex justify-content-between">
                                                            <small class="text-muted">Linked: <?php echo date('M j, Y', strtotime($ext_card['created_at'])); ?></small>
                                                            <button class="btn btn-sm btn-outline-danger" onclick="unlinkCard(<?php echo $ext_card['id']; ?>)">
                                                                <i class="bx bx-unlink"></i> Unlink
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- All Modals -->
<!-- Adjust Balance Modal -->
<div class="modal fade" id="adjustBalanceModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="user_actions.php" method="post">
                                <div class="modal-header">
                    <h5 class="modal-title">Adjust Balance</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="action" value="adjust_balance">
                    <input type="hidden" name="user_id" value="<?php echo $user_id; ?>">
                    
                    <div class="mb-3">
                        <label for="currency" class="form-label">Currency</label>
                        <select class="form-select" name="currency" required>
                            <?php if (empty($balances)): ?>
                                <option value="USD">USD</option>
                            <?php else: ?>
                                <?php foreach ($balances as $b): ?>
                                    <option value="<?php echo htmlspecialchars($b['currency']); ?>"><?php echo htmlspecialchars($b['currency']); ?></option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Type</label>
                        <div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="adjustment_type" id="credit" value="credit" checked>
                                <label class="form-check-label" for="credit">Credit</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="adjustment_type" id="debit" value="debit">
                                <label class="form-check-label" for="debit">Debit</label>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="amount" class="form-label">Amount</label>
                        <input type="number" class="form-control" name="amount" step="0.01" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="description" class="form-label">Reason</label>
                        <textarea class="form-control" name="description" rows="3" required></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Apply</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Reset Password Modal -->
<div class="modal fade" id="resetPasswordModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="user_actions.php" method="post">
                <div class="modal-header">
                    <h5 class="modal-title">Reset Password</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>This will email a new, temporary password to the user. Are you sure?</p>
                    <input type="hidden" name="action" value="reset_password">
                    <input type="hidden" name="user_id" value="<?php echo $user_id; ?>">
                    <input type="hidden" name="user_email" value="<?php echo htmlspecialchars($user['email'] ?? ''); ?>">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Send Reset Email</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Suspend User Modal -->
<div class="modal fade" id="suspendUserModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="user_actions.php" method="post">
                <div class="modal-header">
                    <h5 class="modal-title">Suspend User</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to suspend this user?</p>
                    <input type="hidden" name="action" value="suspend_user">
                    <input type="hidden" name="user_id" value="<?php echo $user_id; ?>">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-warning">Suspend</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Activate User Modal -->
<div class="modal fade" id="activateUserModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="user_actions.php" method="post">
                <div class="modal-header">
                    <h5 class="modal-title">Activate User</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to activate this user?</p>
                    <input type="hidden" name="action" value="activate_user">
                    <input type="hidden" name="user_id" value="<?php echo $user_id; ?>">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-success">Activate</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete User Modal -->
<div class="modal fade" id="deleteUserModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="user_actions.php" method="post">
                <div class="modal-header">
                    <h5 class="modal-title text-danger">Delete User</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p class="text-danger fw-bold">Warning: This action is irreversible.</p>
                    <p>Are you sure you want to permanently delete this user?</p>
                    <input type="hidden" name="action" value="delete_user">
                    <input type="hidden" name="user_id" value="<?php echo $user_id; ?>">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Delete</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Link External Card Modal -->
<div class="modal fade" id="linkCardModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="user_actions.php" method="post">
                <div class="modal-header">
                    <h5 class="modal-title">Link External Card</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="action" value="link_external_card">
                    <input type="hidden" name="user_id" value="<?php echo $user_id; ?>">
                    
                    <div class="mb-3">
                        <label for="card_type" class="form-label">Card Type</label>
                        <select class="form-select" id="card_type" name="card_type" required>
                            <option value="visa">Visa</option>
                            <option value="mastercard">Mastercard</option>
                            <option value="amex">American Express</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="card_number" class="form-label">Card Number</label>
                        <input type="text" class="form-control" id="card_number" name="card_number" required maxlength="19" placeholder="XXXX XXXX XXXX XXXX">
                    </div>
                    <div class="mb-3">
                        <label for="card_holder_name" class="form-label">Card Holder Name</label>
                        <input type="text" class="form-control" id="card_holder_name" name="card_holder_name" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="expiry_month" class="form-label">Expiry Month</label>
                            <select class="form-select" id="expiry_month" name="expiry_month" required>
                                <?php for ($i = 1; $i <= 12; $i++): ?>
                                    <option value="<?php echo $i; ?>"><?php echo sprintf('%02d', $i); ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="expiry_year" class="form-label">Expiry Year</label>
                            <select class="form-select" id="expiry_year" name="expiry_year" required>
                                <?php for ($i = date('Y'); $i <= date('Y') + 10; $i++): ?>
                                    <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="cvv" class="form-label">CVV</label>
                        <input type="password" class="form-control" id="cvv" name="cvv" required maxlength="4" placeholder="XXX">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Link Card</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Document Viewer Modal -->
<div class="modal fade" id="documentViewerModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Document Viewer</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body text-center p-0">
                <div id="documentContainer" class="p-3">
                    <!-- Document will be displayed here -->
                </div>
            </div>
            <div class="modal-footer">
                <a href="#" id="downloadDocumentBtn" class="btn btn-primary" download>
                    <i class="bx bx-download"></i> Download
                </a>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- JavaScript for Copy to Clipboard and Document Viewer -->
<script>
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(function() {
        // Show a tooltip or notification
        const toast = document.createElement('div');
        toast.className = 'position-fixed bottom-0 end-0 p-3';
        toast.style.zIndex = '5';
        toast.innerHTML = `
            <div class="toast align-items-center text-white bg-success border-0" role="alert" aria-live="assertive" aria-atomic="true">
                <div class="d-flex">
                    <div class="toast-body">
                        <i class="bx bx-check me-2"></i> Copied to clipboard!
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
            </div>
        `;
        document.body.appendChild(toast);
        
        const toastEl = new bootstrap.Toast(toast.querySelector('.toast'));
        toastEl.show();
        
        setTimeout(() => {
            toast.remove();
        }, 3000);
    }).catch(function(err) {
        console.error('Could not copy text: ', err);
    });
}

// Function to view document in modal
function viewDocument(documentPath) {
    const documentContainer = document.getElementById('documentContainer');
    const downloadBtn = document.getElementById('downloadDocumentBtn');
    const modal = new bootstrap.Modal(document.getElementById('documentViewerModal'));
    
    // Clear previous content
    documentContainer.innerHTML = '';
    
    // Set download link
    downloadBtn.href = documentPath;
    
    // Check file type
    const fileExtension = documentPath.split('.').pop().toLowerCase();
    
    if (['jpg', 'jpeg', 'png', 'gif'].includes(fileExtension)) {
        // Display image
        const img = document.createElement('img');
        img.src = documentPath;
        img.className = 'img-fluid';
        img.style.maxHeight = '70vh';
        documentContainer.appendChild(img);
    } else if (fileExtension === 'pdf') {
        // Display PDF in iframe
        const iframe = document.createElement('iframe');
        iframe.src = documentPath;
        iframe.width = '100%';
        iframe.height = '70vh';
        iframe.frameBorder = '0';
        documentContainer.appendChild(iframe);
    } else {
        // For other file types, show download prompt
        documentContainer.innerHTML = `
            <div class="p-5">
                <i class="bx bx-file display-1 text-primary"></i>
                <h4 class="mt-3">File cannot be previewed</h4>
                <p class="text-muted">Please download the file to view its contents.</p>
                <button class="btn btn-primary mt-3" onclick="window.open('${documentPath}', '_blank')">
                    <i class="bx bx-download me-2"></i> Download File
                </button>
            </div>
        `;
    }
    
    // Show modal
    modal.show();
}

// Card management functions
function toggleCardStatus(cardId, action) {
    if (confirm(`Are you sure you want to ${action} this card?`)) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = 'user_actions.php';
        
        const actionInput = document.createElement('input');
        actionInput.type = 'hidden';
        actionInput.name = 'action';
        actionInput.value = 'toggle_card_status';
        
        const cardIdInput = document.createElement('input');
        cardIdInput.type = 'hidden';
        cardIdInput.name = 'card_id';
        cardIdInput.value = cardId;
        
        const userIdInput = document.createElement('input');
        userIdInput.type = 'hidden';
        userIdInput.name = 'user_id';
        userIdInput.value = <?php echo $user_id; ?>;
        
        const statusInput = document.createElement('input');
        statusInput.type = 'hidden';
        statusInput.name = 'status';
        statusInput.value = action === 'freeze' ? 'frozen' : 'active';
        
        form.appendChild(actionInput);
        form.appendChild(cardIdInput);
        form.appendChild(userIdInput);
        form.appendChild(statusInput);
        
        document.body.appendChild(form);
        form.submit();
    }
}

function deleteCard(cardId) {
    if (confirm('Are you sure you want to delete this card? This action cannot be undone.')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = 'user_actions.php';
        
        const actionInput = document.createElement('input');
        actionInput.type = 'hidden';
        actionInput.name = 'action';
        actionInput.value = 'delete_card';
        
        const cardIdInput = document.createElement('input');
        cardIdInput.type = 'hidden';
        cardIdInput.name = 'card_id';
        cardIdInput.value = cardId;
        
        const userIdInput = document.createElement('input');
        userIdInput.type = 'hidden';
        userIdInput.name = 'user_id';
        userIdInput.value = <?php echo $user_id; ?>;
        
        form.appendChild(actionInput);
        form.appendChild(cardIdInput);
        form.appendChild(userIdInput);
        
        document.body.appendChild(form);
        form.submit();
    }
}

function unlinkCard(cardId) {
    if (confirm('Are you sure you want to unlink this external card?')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = 'user_actions.php';
        
        const actionInput = document.createElement('input');
        actionInput.type = 'hidden';
        actionInput.name = 'action';
        actionInput.value = 'unlink_external_card';
        
        const cardIdInput = document.createElement('input');
        cardIdInput.type = 'hidden';
        cardIdInput.name = 'ext_card_id';
        cardIdInput.value = cardId;
        
        const userIdInput = document.createElement('input');
        userIdInput.type = 'hidden';
        userIdInput.name = 'user_id';
        userIdInput.value = <?php echo $user_id; ?>;
        
        form.appendChild(actionInput);
        form.appendChild(cardIdInput);
        form.appendChild(userIdInput);
        
        document.body.appendChild(form);
        form.submit();
    }
}

// Format card number input with spaces
document.getElementById('card_number')?.addEventListener('input', function(e) {
    let value = e.target.value.replace(/\D/g, '');
    let formattedValue = '';
    
    for (let i = 0; i < value.length; i++) {
        if (i > 0 && i % 4 === 0) {
            formattedValue += ' ';
        }
        formattedValue += value[i];
    }
    
    e.target.value = formattedValue;
});
</script>

<style>
/* Card styles for admin view */
.card-container {
    perspective: 1000px;
    height: 200px;
}
.card-inner {
    position: relative;
    width: 100%;
    height: 100%;
    transition: transform 0.6s;
    transform-style: preserve-3d;
}
.card-front {
    position: absolute;
    width: 100%;
    height: 100%;
    backface-visibility: hidden;
    border-radius: 1rem;
    padding: 1.5rem;
    color: white;
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.card-front.visa {
    background: linear-gradient(135deg, #1a1f71, #5b65d9);
}
.card-front.mastercard {
    background: linear-gradient(135deg, #000000, #4a4a4a);
}
.card-front.amex {
    background: linear-gradient(135deg, #006fcf, #65a9e0);
}
.external-card {
    background: linear-gradient(135deg, #64748b, #94a3b8);
    position: relative;
}
.external-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><rect width="100" height="100" fill="none" stroke="%23ffffff" stroke-width="2" stroke-dasharray="5,5" opacity="0.2"/></svg>');
    opacity: 0.1;
}
</style>

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