<?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 = [];
$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()); }
    }
}

include 'includes/header.php';
?>

<div class="content-wrapper">
    <div class="container-fluid">
        <!-- Page Header -->
        <div class="page-header">
            <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 justify-content-end mb-3">
            <a href="manage_users.php" class="btn btn-sm btn-secondary me-2">Back to Users</a>
            <a href="edit_user.php?id=<?php echo $user_id; ?>" class="btn btn-sm btn-warning me-2">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">Adjust Balance</a></li>
                    <li><a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#resetPasswordModal">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">Suspend User</a></li>
                    <?php else: ?>
                        <li><a class="dropdown-item text-success" href="#" data-bs-toggle="modal" data-bs-target="#activateUserModal">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">Delete User</a></li>
                </ul>
            </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">
                        <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 mb-3" style="width: 120px; height: 120px; object-fit: cover;">
                        <h5 class="my-3"><?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?></h5>
                        <p class="text-muted mb-1"><?php echo htmlspecialchars($user['email']); ?></p>
                        <p class="text-muted mb-4"><?php echo htmlspecialchars($user['country'] ?? 'N/A'); ?></p>
                    </div>
                </div>

                <!-- Account Balances Card -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="card-title">Account Balances</h5>
                    </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">
                                        <strong><?php echo htmlspecialchars($balance['currency']); ?></strong>
                                        <span><?php echo number_format($balance['balance'], ($balance['currency'] === 'BTC' ? 8 : 2)); ?></span>
                                    </li>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </ul>
                    </div>
                    <div class="card-footer">
                        <button class="btn btn-sm btn-primary w-100" data-bs-toggle="modal" data-bs-target="#adjustBalanceModal">Adjust Balance</button>
                    </div>
                </div>
            </div>

            <!-- Right Column -->
            <div class="col-lg-8">
                <!-- Personal Information Card -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="card-title">Personal Information</h5>
                    </div>
                    <div class="card-body">
                        <div class="row mb-2"><div class="col-sm-4 text-muted">Full Name</div><div class="col-sm-8"><?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?></div></div>
                        <div class="row mb-2"><div class="col-sm-4 text-muted">Email</div><div class="col-sm-8"><?php echo htmlspecialchars($user['email']); ?></div></div>
                        <div class="row mb-2"><div class="col-sm-4 text-muted">Phone</div><div class="col-sm-8"><?php echo htmlspecialchars($user['phone'] ?? 'N/A'); ?></div></div>
                        <div class="row mb-2"><div class="col-sm-4 text-muted">Date of Birth</div><div class="col-sm-8"><?php echo date('F j, Y', strtotime($user['date_of_birth'] ?? 'now')); ?></div></div>
                        <div class="row mb-2"><div class="col-sm-4 text-muted">Account Number</div><div class="col-sm-8"><?php echo htmlspecialchars($user['account_number'] ?? 'N/A'); ?></div></div>
                        <div class="row mb-2"><div class="col-sm-4 text-muted">Status</div><div class="col-sm-8"><span class="badge bg-<?php echo ($user['status'] == 'active' ? 'success' : 'warning'); ?>"><?php echo ucfirst($user['status'] ?? 'N/A'); ?></span></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">Next of Kin</h5>
                    </div>
                    <div class="card-body">
                        <div class="row mb-2"><div class="col-sm-4 text-muted">Name</div><div class="col-sm-8"><?php echo htmlspecialchars($kin['full_name'] ?? 'N/A'); ?></div></div>
                        <div class="row mb-2"><div class="col-sm-4 text-muted">Relationship</div><div class="col-sm-8"><?php echo htmlspecialchars($kin['relationship'] ?? 'N/A'); ?></div></div>
                        <div class="row mb-2"><div class="col-sm-4 text-muted">Email</div><div class="col-sm-8"><?php echo htmlspecialchars($kin['email'] ?? 'N/A'); ?></div></div>
                        <div class="row mb-2"><div class="col-sm-4 text-muted">Phone</div><div class="col-sm-8"><?php echo htmlspecialchars($kin['phone'] ?? 'N/A'); ?></div></div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Recent Transactions Table -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title">Recent Transactions</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Date</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>
        <?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>


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