<?php
session_start();
require_once 'php/adminconfig.php';
// Enhanced login and role check
if (!isset($_SESSION['admin_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: signin-admin.php');
    exit();
}
// Simple logout
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    session_destroy();
    header('Location: signin-admin.php');
    exit();
}

// Fetch all users from the database
$query = "SELECT * FROM users ORDER BY id DESC";
$stmt = $conn->prepare($query);
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Handle user deletion
if (isset($_POST['delete_user']) && isset($_POST['user_id'])) {
    $user_id = intval($_POST['user_id']);
    
    try {
        $delete_query = "DELETE FROM users WHERE id = :user_id";
        $delete_stmt = $conn->prepare($delete_query);
        $delete_stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
        $delete_stmt->execute();
        
        // Set success message
        $_SESSION['success_message'] = "User deleted successfully";
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit();
    } catch (PDOException $e) {
        $_SESSION['error_message'] = "Error deleting user: " . $e->getMessage();
    }
}

// Handle user data update
if (isset($_POST['update_user']) && isset($_POST['user_id'])) {
    $user_id = intval($_POST['user_id']);
    
    // Get all fields from the form excluding user_id and update_user
    $updateFields = [];
    $params = [];
    
    foreach ($_POST as $key => $value) {
        if ($key !== 'user_id' && $key !== 'update_user') {
            $updateFields[] = "$key = :$key";
            $params[":$key"] = $value;
        }
    }
    
    if (!empty($updateFields)) {
        try {
            $update_query = "UPDATE users SET " . implode(", ", $updateFields) . " WHERE id = :user_id";
            $update_stmt = $conn->prepare($update_query);
            $update_stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
            
            foreach ($params as $param => $value) {
                $update_stmt->bindValue($param, $value);
            }
            
            $update_stmt->execute();
            
            // Set success message
            $_SESSION['success_message'] = "User updated successfully";
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit();
        } catch (PDOException $e) {
            $_SESSION['error_message'] = "Error updating user: " . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9, user-scalable=no" />
    <title>TradeWave PLC - Admin-users-Dashboard</title>
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Chart.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
    <!-- ApexCharts -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/apexcharts/3.36.3/apexcharts.min.js"></script>
    <link rel="stylesheet" type="text/css" href="css/admin.css">
    <style>
        :root {
            --primary-color: #6c5ce7;
            --secondary-color: #8e44ad;
            --success-color: #27ae60;
            --danger-color: #e74c3c;
            --light-color: #f5f6fa;
            --dark-color: #2c3e50;
            --border-color: #dcdde1;
        }


        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        
        .containerrr {
            padding: 20px;
            width: 100%;
        }
        
        .page-title {
            color: var(--dark-color);
            margin-bottom: 20px;
            font-size: 1.5rem;
            background: #f9f9f9;
            font-weight: 500;
        }
        
        .user-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
        }
        
        .user-card {
            background-color: #f4f4f4;
            border-radius: 0 10px 10px 0;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
            padding: 15px;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
            position: relative;
            border-left: 4px solid rgba(123, 31, 162, 0.5);
        }
        
        .user-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
        }
        
        .user-card.active {
            border-color: green;
            background-color: #eee;
        }
        
        .user-icon {
            width: 50px;
            height: 50px;
            background-color: rgba(0,0,0,0.4);
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            float: left;
            margin-right: 15px;
            font-size: 24px;
        }
        
        .user-name {
            font-weight: bold;
            font-size: 18px;
            margin-bottom: 5px;
            color: var(--dark-color);
        }
        
        .user-email {
            color: #666;
            font-size: 14px;
            margin-bottom: 10px;
            word-break: break-all;
        }
        
        .user-balance {
            color: var(--success-color);
            font-weight: bold;
            font-size: 16px;
            margin-bottom: 5px;
        }
        
        .user-created {
            color: #999;
            font-size: 12px;
            position: absolute;
            bottom: 10px;
            right: 15px;
        }
        
        .user-details {
            background-color: rgba(0,0,0,0.6);
            border-radius: 5px;
            box-shadow: 0 3px 15px rgba(0, 0, 0, 0.1);
            margin-top: 20px;
            margin-bottom: 40px;
            padding: 10px;
            position: relative;
            display: none;
        }
        
        .user-details.active {
            display: block;
        }
        
        .user-details h3 {
            color: var(--secondary-color);
            margin-bottom: 30px;
            padding: 10px;
            background: #fff;
            border-radius: 8px;
            width: 50%;
        }
        
        .edit-form {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }
        
        @media (max-width: 768px) {
            .edit-form {
                grid-template-columns: 1fr;
            }
            
            .user-grid {
                grid-template-columns: 1fr;
            }
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: white;
            font-weight: 500;
        }
        
        .form-control {
            width: 100%;
            padding: 10px 15px;
            border: 1px solid var(--border-color);
            border-radius: 10px 10px 0 0;
            border-bottom: 3px solid purple;
            font-size: 14px;
        }
        
        .btn {
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: background-color 0.2s;
        }
        
        .btn-primary {
            background-color: purple;
            color: white;
        }
        
        .btn-primary:hover {
            background-color: var(--secondary-color);
        }
        
        .btn-danger {
            background-color: var(--danger-color);
            color: white;
        }
        
        .btn-danger:hover {
            background-color: #c0392b;
        }
        
        .delete-btn {
            position: absolute;
            top: 20px;
            right: 20px;
        }
        
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            align-items: center;
            justify-content: center;
        }
        
        .modal-content {
            background-color: white;
            border-radius: 8px;
            width: 90%;
            max-width: 400px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.2);
        }
        
        .warning-icon {
            font-size: 48px;
            color: #f39c12;
            margin-bottom: 15px;
        }
        
        .modal-title {
            font-size: 20px;
            margin-bottom: 15px;
            color: var(--dark-color);
        }
        
        .modal-text {
            margin-bottom: 20px;
            color: #555;
        }
        
        .modal-actions {
            display: flex;
            justify-content: center;
            gap: 10px;
        }
        
        .alert {
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 4px;
            color: white;
        }
        
        .alert-success {
            background-color: var(--success-color);
        }
        
        .alert-danger {
            background-color: var(--danger-color);
        }
        
        .close-alert {
            float: right;
            cursor: pointer;
            font-weight: bold;
        }
        
        .submit-row {
            grid-column: 1 / -1;
            margin-top: 15px;
        }
    </style>
</head>
<body>

    <?php include "required/admin-nav.php" ?>

    <div class="pc">
    <div class="containerrr">
        <h2 class="page-title">User Management</h2>
        
        <?php if (isset($_SESSION['success_message'])): ?>
            <div class="alert alert-success">
                <span class="close-alert">&times;</span>
                <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
            </div>
        <?php endif; ?>
        
        <?php if (isset($_SESSION['error_message'])): ?>
            <div class="alert alert-danger">
                <span class="close-alert">&times;</span>
                <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
            </div>
        <?php endif; ?>
        
        <div class="user-grid">
            <?php foreach ($users as $user): ?>
                <div class="user-card" data-id="<?php echo $user['id']; ?>">
                    <div class="user-icon">
                        <i class="fas fa-user"></i>
                    </div>
                    <div class="user-name"><?php echo htmlspecialchars($user['firstname'] . ' ' . $user['lastname']); ?></div>
                    <div class="user-email"><?php echo htmlspecialchars($user['email']); ?></div>
                    <div class="user-balance"><?php echo $user['currency_symbol'] ?? '$'; ?><?php echo number_format($user['total_balance'], 2); ?></div>
                    <div class="user-created">
                        <?php 
                        // Get registration date from ID if no explicit date field
                        $timestamp = isset($user['created_at']) ? strtotime($user['created_at']) : $user['id'] / 1000;
                        echo date('M d, Y', $timestamp); 
                        ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        
        <?php foreach ($users as $user): ?>
            <div class="user-details" id="details-<?php echo $user['id']; ?>">
                <h3>Edit User: <?php echo htmlspecialchars($user['firstname'] . ' ' . $user['lastname']); ?></h3>
                <button class="btn btn-danger delete-btn" data-id="<?php echo $user['id']; ?>">Delete User</button>
                
                <form action="" method="POST" class="edit-form">
                    <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                    
                    <?php 
                    // Dynamically generate form fields based on database columns
                    $excludeFields = ['id', 'password', 'profile_photo', 'id_photo']; 
                    
                    foreach ($user as $field => $value):
                        if (!in_array($field, $excludeFields)):
                    ?>
                        <div class="form-group">
                            <label for="<?php echo $field; ?>"><?php echo ucwords(str_replace('_', ' ', $field)); ?></label>
                            <?php if ($field == 'status'): ?>
                                <select name="<?php echo $field; ?>" id="<?php echo $field; ?>" class="form-control">
                                    <option value="Pending" <?php echo $value == 'Pending' ? 'selected' : ''; ?>>Pending</option>
                                    <option value="Active" <?php echo $value == 'Active' ? 'selected' : ''; ?>>Active</option>
                                    <option value="suspended" <?php echo $value == 'suspended' ? 'selected' : ''; ?>>suspended</option>
                                    <option value="Blocked" <?php echo $value == 'Blocked' ? 'selected' : ''; ?>>Blocked</option>
                                </select>
                            <?php elseif ($field == 'role'): ?>
                                <select name="<?php echo $field; ?>" id="<?php echo $field; ?>" class="form-control">
                                    <option value="user" <?php echo $value == 'user' ? 'selected' : ''; ?>>User</option>
                                    <option value="admin" <?php echo $value == 'admin' ? 'selected' : ''; ?>>Admin</option>
                                </select>
                            <?php elseif ($field == 'account_type'): ?>
                                <select name="<?php echo $field; ?>" id="<?php echo $field; ?>" class="form-control">
                                    <option value="Personal" <?php echo $value == 'Personal' ? 'selected' : ''; ?>>Personal</option>
                                    <option value="Business" <?php echo $value == 'Business' ? 'selected' : ''; ?>>Business</option>
                                    <option value="Corporate" <?php echo $value == 'Corporate' ? 'selected' : ''; ?>>Corporate</option>
                                </select>
                            <?php elseif ($field == 'package_plan'): ?>
                                <select name="<?php echo $field; ?>" id="<?php echo $field; ?>" class="form-control">
                                    <option value="Inactive" <?php echo $value == 'Inactive' ? 'selected' : ''; ?>>Inactive</option>
                                    <option value="Starlite" <?php echo $value == 'Starlite' ? 'selected' : ''; ?>>Starlite</option>
                                    <option value="Elite" <?php echo $value == 'Elite' ? 'selected' : ''; ?>>Elite</option>
                                    <option value="Plantinium" <?php echo $value == 'Plantinium' ? 'selected' : ''; ?>>Plantinium</option>
                                    <option value="Diamond" <?php echo $value == 'Diamond' ? 'selected' : ''; ?>>Diamond</option>
                                </select>
                            <?php elseif ($field == 'date_of_birth'): ?>
                                <input type="date" name="<?php echo $field; ?>" id="<?php echo $field; ?>" class="form-control" value="<?php echo htmlspecialchars($value); ?>">
                            <?php else: ?>
                                <input type="text" name="<?php echo $field; ?>" id="<?php echo $field; ?>" class="form-control" value="<?php echo htmlspecialchars($value); ?>">
                            <?php endif; ?>
                        </div>
                    <?php 
                        endif;
                    endforeach; 
                    ?>
                    
                    <div class="form-group submit-row">
                        <button type="submit" name="update_user" class="btn btn-primary">Update User</button>
                    </div>
                </form>
            </div>
        <?php endforeach; ?>
        
        <!-- Delete Confirmation Modal -->
        <div class="modal" id="deleteModal">
            <div class="modal-content">
                <div class="warning-icon">
                    <i class="fas fa-exclamation-triangle"></i>
                </div>
                <h3 class="modal-title">Delete User</h3>
                <p class="modal-text">Are you sure you want to delete this user from database?</p>
                <div class="modal-actions">
                    <form id="deleteForm" action="" method="POST">
                        <input type="hidden" name="user_id" id="deleteUserId">
                        <button type="submit" name="delete_user" class="btn btn-danger">Yes, Delete</button>
                    </form>
                    <button class="btn btn-primary" id="cancelDelete">Cancel</button>
                </div>
            </div>
        </div>
    </div>
</div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // User card click handler
            const userCards = document.querySelectorAll('.user-card');
            userCards.forEach(card => {
                card.addEventListener('click', function() {
                    const userId = this.getAttribute('data-id');
                    
                    // Hide all details sections
                    document.querySelectorAll('.user-details').forEach(detail => {
                        detail.classList.remove('active');
                    });
                    
                    // Remove active class from all cards
                    userCards.forEach(c => {
                        c.classList.remove('active');
                    });
                    
                    // Show the clicked user's details
                    document.getElementById('details-' + userId).classList.add('active');
                    
                    // Add active class to the clicked card
                    this.classList.add('active');
                    
                    // Scroll to the details section
                    document.getElementById('details-' + userId).scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                });
            });
            
            // Delete button click handler
            const deleteButtons = document.querySelectorAll('.delete-btn');
            const deleteModal = document.getElementById('deleteModal');
            const deleteForm = document.getElementById('deleteForm');
            const deleteUserId = document.getElementById('deleteUserId');
            const cancelDelete = document.getElementById('cancelDelete');
            
            deleteButtons.forEach(button => {
                button.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    const userId = this.getAttribute('data-id');
                    deleteUserId.value = userId;
                    deleteModal.style.display = 'flex';
                });
            });
            
            // Cancel delete button
            cancelDelete.addEventListener('click', function() {
                deleteModal.style.display = 'none';
            });
            
            // Close modal if clicked outside
            window.addEventListener('click', function(e) {
                if (e.target === deleteModal) {
                    deleteModal.style.display = 'none';
                }
            });
            
            // Close alerts
            const closeAlerts = document.querySelectorAll('.close-alert');
            closeAlerts.forEach(btn => {
                btn.addEventListener('click', function() {
                    this.parentElement.style.display = 'none';
                });
            });
        });
    </script>
</body>
</html>
