<?php
$page_title = "Edit User";
require_once 'header.php';

$db = Database::getInstance()->connect();
$user_id = $_GET['id'] ?? 0;

if (!$user_id) {
    header("Location: users.php");
    exit();
}

// Get user data
$stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

if (!$user) {
    header("Location: users.php");
    exit();
}

// Get user statistics
$stats_stmt = $db->prepare("
    SELECT 
        (SELECT COUNT(*) FROM investments WHERE user_id = ?) as total_investments,
        (SELECT SUM(amount) FROM investments WHERE user_id = ?) as total_invested,
        (SELECT COUNT(*) FROM transactions WHERE user_id = ?) as total_transactions,
        (SELECT COUNT(*) FROM support_tickets WHERE user_id = ?) as total_tickets
");
$stats_stmt->execute([$user_id, $user_id, $user_id, $user_id]);
$stats = $stats_stmt->fetch();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $full_name = $_POST['full_name'] ?? '';
    $email = $_POST['email'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $country = $_POST['country'] ?? '';
    $city = $_POST['city'] ?? '';
    $address = $_POST['address'] ?? '';
    $account_status = $_POST['account_status'] ?? '';
    $balance = floatval($_POST['balance'] ?? 0);
    $total_deposit = floatval($_POST['total_deposit'] ?? 0);
    $total_withdrawal = floatval($_POST['total_withdrawal'] ?? 0);
    $profit_balance = floatval($_POST['profit_balance'] ?? 0);
    $referral_balance = floatval($_POST['referral_balance'] ?? 0);
    $email_verified = isset($_POST['email_verified']) ? 1 : 0;
    $kyc_status = $_POST['kyc_status'] ?? '';
    
    // Validate email
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Invalid email address";
    } elseif ($email != $user['email']) {
        // Check if email exists
        $check_stmt = $db->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
        $check_stmt->execute([$email, $user_id]);
        if ($check_stmt->rowCount() > 0) {
            $error = "Email already exists";
        }
    }
    
    if (!isset($error)) {
        try {
            $db->beginTransaction();
            
            // Update user
            $update_stmt = $db->prepare("
                UPDATE users SET
                    full_name = ?,
                    email = ?,
                    phone = ?,
                    country = ?,
                    city = ?,
                    address = ?,
                    account_status = ?,
                    balance = ?,
                    total_deposit = ?,
                    total_withdrawal = ?,
                    profit_balance = ?,
                    referral_balance = ?,
                    email_verified = ?,
                    kyc_status = ?
                WHERE id = ?
            ");
            
            $update_stmt->execute([
                $full_name, $email, $phone, $country, $city, $address,
                $account_status, $balance, $total_deposit, $total_withdrawal,
                $profit_balance, $referral_balance, $email_verified, $kyc_status,
                $user_id
            ]);
            
            // Log the action
            $log_stmt = $db->prepare("
                INSERT INTO activity_logs (admin_id, user_id, action, description, ip_address, user_agent, details, created_at)
                VALUES (?, ?, 'user_update', 'User profile updated', ?, ?, ?, NOW())
            ");

            $log_stmt->execute([
                $_SESSION['admin_id'],
                $user_id,
                $_SERVER['REMOTE_ADDR'] ?? '',
                $_SERVER['HTTP_USER_AGENT'] ?? '',
                json_encode([
                    'old_balance' => $user['balance'],
                    'new_balance' => $balance,
                    'changed_by' => $_SESSION['admin_username']
                ])
            ]);
            
            $db->commit();
            $success = "User updated successfully!";
            
            // Refresh user data
            $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
            $stmt->execute([$user_id]);
            $user = $stmt->fetch();
            
        } catch (Exception $e) {
            $db->rollBack();
            $error = "Update failed: " . $e->getMessage();
        }
    }
}

// Handle manual balance adjustment
if (isset($_POST['adjust_balance'])) {
    $amount = floatval($_POST['adjust_amount']);
    $type = $_POST['adjust_type'];
    $reason = $_POST['adjust_reason'];
    
    if ($amount <= 0) {
        $adjust_error = "Amount must be positive";
    } else {
        try {
            $db->beginTransaction();
            
            // Calculate new balance
            $new_balance = $type == 'add' ? $user['balance'] + $amount : $user['balance'] - $amount;
            
            // Update user balance
            $update_stmt = $db->prepare("UPDATE users SET balance = ? WHERE id = ?");
            $update_stmt->execute([$new_balance, $user_id]);
            
            // Create transaction record
            $transaction_type = $type == 'add' ? 'credit' : 'debit';
            $reference = 'ADJ' . time() . rand(1000, 9999);
            
            $tx_stmt = $db->prepare("
                INSERT INTO transactions (user_id, type, amount, method, description, reference, status, admin_action_by)
                VALUES (?, ?, ?, 'manual_adjustment', ?, ?, 'completed', ?)
            ");
            
            $tx_stmt->execute([
                $user_id,
                $transaction_type,
                $amount,
                "Manual adjustment: $reason",
                $reference,
                $_SESSION['admin_id']
            ]);
            
            // Log the action
            $log_stmt = $db->prepare("
                INSERT INTO activity_logs (admin_id, user_id, action, description, ip_address, user_agent, details, created_at)
                VALUES (?, ?, 'balance_adjustment', 'User balance adjusted', ?, ?, ?, NOW())
            ");

            $log_stmt->execute([
                $_SESSION['admin_id'],
                $user_id,
                $_SERVER['REMOTE_ADDR'] ?? '',
                $_SERVER['HTTP_USER_AGENT'] ?? '',
                json_encode([
                    'amount' => $amount,
                    'type' => $type,
                    'reason' => $reason,
                    'old_balance' => $user['balance'],
                    'new_balance' => $new_balance
                ])
            ]);
            
            $db->commit();
            $adjust_success = "Balance adjusted successfully!";
            
            // Refresh user data
            $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
            $stmt->execute([$user_id]);
            $user = $stmt->fetch();
            
        } catch (Exception $e) {
            $db->rollBack();
            $adjust_error = "Adjustment failed: " . $e->getMessage();
        }
    }
}
?>

<div class="container-fluid">
    <!-- User Header -->
    <div class="bg-white rounded-xl shadow p-6 mb-6">
        <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
            <div class="flex items-center space-x-4">
                <div class="w-20 h-20 bg-gradient-to-r from-purple-500 to-blue-500 rounded-full flex items-center justify-center text-white text-2xl font-bold">
                    <?php echo strtoupper(substr($user['username'], 0, 1)); ?>
                </div>
                <div>
                    <h2 class="text-2xl font-bold"><?php echo htmlspecialchars($user['username']); ?></h2>
                    <p class="text-gray-600">User ID: <?php echo $user['id']; ?></p>
                    <p class="text-gray-600">Member since: <?php echo date('F j, Y', strtotime($user['created_at'])); ?></p>
                </div>
            </div>
            
            <div class="flex flex-wrap gap-2">
                <a href="../user/dashboard.php?admin_view=<?php echo $user_id; ?>" target="_blank"
                   class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
                    <i class="fas fa-eye mr-2"></i>View as User
                </a>
                <a href="transactions.php?user_id=<?php echo $user_id; ?>"
                   class="bg-purple-600 text-white px-4 py-2 rounded-lg hover:bg-purple-700">
                    <i class="fas fa-history mr-2"></i>View Transactions
                </a>
                <a href="investments.php?user_id=<?php echo $user_id; ?>"
                   class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700">
                    <i class="fas fa-chart-pie mr-2"></i>View Investments
                </a>
            </div>
        </div>
    </div>

    <!-- Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600">Account Balance</p>
                    <h3 class="text-2xl font-bold text-green-600">$<?php echo number_format($user['balance'], 2); ?></h3>
                </div>
                <i class="fas fa-wallet text-green-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600">Total Invested</p>
                    <h3 class="text-2xl font-bold text-blue-600">$<?php echo number_format($stats['total_invested'] ?? 0, 2); ?></h3>
                </div>
                <i class="fas fa-chart-pie text-blue-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600">Total Transactions</p>
                    <h3 class="text-2xl font-bold text-purple-600"><?php echo number_format($stats['total_transactions'] ?? 0); ?></h3>
                </div>
                <i class="fas fa-exchange-alt text-purple-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600">Support Tickets</p>
                    <h3 class="text-2xl font-bold text-yellow-600"><?php echo number_format($stats['total_tickets'] ?? 0); ?></h3>
                </div>
                <i class="fas fa-headset text-yellow-500 text-2xl"></i>
            </div>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Edit Form -->
        <div class="lg:col-span-2">
            <div class="bg-white rounded-xl shadow p-6">
                <h3 class="text-xl font-bold mb-6">Edit User Information</h3>
                
                <?php if (isset($error)): ?>
                <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
                    <?php echo $error; ?>
                </div>
                <?php endif; ?>
                
                <?php if (isset($success)): ?>
                <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
                    <?php echo $success; ?>
                </div>
                <?php endif; ?>
                
                <form method="POST" action="" class="space-y-6">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Username</label>
                            <input type="text" value="<?php echo htmlspecialchars($user['username']); ?>" 
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg bg-gray-100" readonly>
                            <p class="text-xs text-gray-500 mt-1">Username cannot be changed</p>
                        </div>
                        
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Email Address *</label>
                            <input type="email" name="email" value="<?php echo htmlspecialchars($user['email']); ?>" required
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                        </div>
                    </div>
                    
                    <div>
                        <label class="block text-gray-700 font-medium mb-2">Full Name</label>
                        <input type="text" name="full_name" value="<?php echo htmlspecialchars($user['full_name'] ?? ''); ?>"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                    </div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Phone Number</label>
                            <input type="text" name="phone" value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>"
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                        </div>
                        
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Country</label>
                            <select name="country" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                                <option value="">Select Country</option>
                                <option value="US" <?php echo ($user['country'] ?? '') == 'US' ? 'selected' : ''; ?>>United States</option>
                                <option value="UK" <?php echo ($user['country'] ?? '') == 'UK' ? 'selected' : ''; ?>>United Kingdom</option>
                                <option value="CA" <?php echo ($user['country'] ?? '') == 'CA' ? 'selected' : ''; ?>>Canada</option>
                                <option value="AU" <?php echo ($user['country'] ?? '') == 'AU' ? 'selected' : ''; ?>>Australia</option>
                                <!-- Add more countries as needed -->
                            </select>
                        </div>
                    </div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">City</label>
                            <input type="text" name="city" value="<?php echo htmlspecialchars($user['city'] ?? ''); ?>"
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                        </div>
                        
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Address</label>
                            <input type="text" name="address" value="<?php echo htmlspecialchars($user['address'] ?? ''); ?>"
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                        </div>
                    </div>
                    
                    <!-- Account Status -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Account Status</label>
                            <select name="account_status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                                <option value="pending" <?php echo $user['account_status'] == 'pending' ? 'selected' : ''; ?>>Pending</option>
                                <option value="active" <?php echo $user['account_status'] == 'active' ? 'selected' : ''; ?>>Active</option>
                                <option value="suspended" <?php echo $user['account_status'] == 'suspended' ? 'selected' : ''; ?>>Suspended</option>
                                <option value="blocked" <?php echo $user['account_status'] == 'blocked' ? 'selected' : ''; ?>>Blocked</option>
                            </select>
                        </div>
                        
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">KYC Status</label>
                            <select name="kyc_status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                                <option value="pending" <?php echo ($user['kyc_status'] ?? 'pending') == 'pending' ? 'selected' : ''; ?>>Pending</option>
                                <option value="verified" <?php echo ($user['kyc_status'] ?? 'pending') == 'verified' ? 'selected' : ''; ?>>Verified</option>
                                <option value="rejected" <?php echo ($user['kyc_status'] ?? 'pending') == 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                            </select>
                        </div>
                    </div>
                    
                    <!-- Financial Information -->
                    <div class="border-t pt-6">
                        <h4 class="text-lg font-bold mb-4">Financial Information</h4>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-gray-700 font-medium mb-2">Account Balance ($)</label>
                                <input type="number" step="0.01" name="balance" value="<?php echo number_format($user['balance'], 2, '.', ''); ?>"
                                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                            </div>
                            
                            <div>
                                <label class="block text-gray-700 font-medium mb-2">Total Deposit ($)</label>
                                <input type="number" step="0.01" name="total_deposit" value="<?php echo number_format($user['total_deposit'], 2, '.', ''); ?>"
                                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                            </div>
                            
                            <div>
                                <label class="block text-gray-700 font-medium mb-2">Total Withdrawal ($)</label>
                                <input type="number" step="0.01" name="total_withdrawal" value="<?php echo number_format($user['total_withdrawal'], 2, '.', ''); ?>"
                                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                            </div>
                            
                            <div>
                                <label class="block text-gray-700 font-medium mb-2">Profit Balance ($)</label>
                                <input type="number" step="0.01" name="profit_balance" value="<?php echo number_format($user['profit_balance'], 2, '.', ''); ?>"
                                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                            </div>
                            
                            <div>
                                <label class="block text-gray-700 font-medium mb-2">Referral Balance ($)</label>
                                <input type="number" step="0.01" name="referral_balance" value="<?php echo number_format($user['referral_balance'], 2, '.', ''); ?>"
                                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                            </div>
                        </div>
                    </div>
                    
                    <!-- Verification -->
                    <div class="border-t pt-6">
                        <div class="flex items-center">
                            <input type="checkbox" id="email_verified" name="email_verified" value="1" 
                                   <?php echo $user['email_verified'] ? 'checked' : ''; ?>
                                   class="h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded">
                            <label for="email_verified" class="ml-2 text-gray-700">
                                Email Verified
                            </label>
                        </div>
                    </div>
                    
                    <!-- Submit -->
                    <div class="border-t pt-6">
                        <button type="submit" 
                                class="w-full bg-gradient-to-r from-purple-600 to-blue-600 text-white font-bold py-3 px-4 rounded-lg hover:opacity-90">
                            <i class="fas fa-save mr-2"></i>Save Changes
                        </button>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- Sidebar: Quick Actions -->
        <div class="space-y-6">
            <!-- Balance Adjustment -->
            <div class="bg-white rounded-xl shadow p-6">
                <h4 class="text-lg font-bold mb-4">Balance Adjustment</h4>
                
                <?php if (isset($adjust_error)): ?>
                <div class="bg-red-100 border border-red-400 text-red-700 px-3 py-2 rounded mb-3 text-sm">
                    <?php echo $adjust_error; ?>
                </div>
                <?php endif; ?>
                
                <?php if (isset($adjust_success)): ?>
                <div class="bg-green-100 border border-green-400 text-green-700 px-3 py-2 rounded mb-3 text-sm">
                    <?php echo $adjust_success; ?>
                </div>
                <?php endif; ?>
                
                <form method="POST" action="" class="space-y-4">
                    <div>
                        <label class="block text-gray-700 text-sm mb-1">Amount ($)</label>
                        <input type="number" step="0.01" name="adjust_amount" required
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                    </div>
                    
                    <div>
                        <label class="block text-gray-700 text-sm mb-1">Type</label>
                        <select name="adjust_type" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                            <option value="add">Add to Balance</option>
                            <option value="subtract">Subtract from Balance</option>
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-gray-700 text-sm mb-1">Reason</label>
                        <textarea name="adjust_reason" rows="3" required
                                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                                  placeholder="Enter reason for adjustment"></textarea>
                    </div>
                    
                    <button type="submit" name="adjust_balance"
                            class="w-full bg-gray-800 text-white py-2 rounded-lg hover:bg-gray-900">
                        <i class="fas fa-exchange-alt mr-2"></i>Adjust Balance
                    </button>
                </form>
            </div>
            
            <!-- Quick Actions -->
            <div class="bg-white rounded-xl shadow p-6">
                <h4 class="text-lg font-bold mb-4">Quick Actions</h4>
                <div class="space-y-3">
                    <a href="?action=reset_password&id=<?php echo $user_id; ?>" 
                       onclick="return confirm('Reset user password? A new password will be emailed to them.')"
                       class="block bg-blue-50 hover:bg-blue-100 text-blue-700 px-4 py-3 rounded-lg">
                        <i class="fas fa-key mr-2"></i>Reset Password
                    </a>
                    
                    <a href="?action=send_email&id=<?php echo $user_id; ?>" 
                       class="block bg-green-50 hover:bg-green-100 text-green-700 px-4 py-3 rounded-lg">
                        <i class="fas fa-envelope mr-2"></i>Send Email
                    </a>
                    
                    <?php if ($user['account_status'] == 'active'): ?>
                    <a href="?action=suspend&id=<?php echo $user_id; ?>" 
                       onclick="return confirm('Suspend this user? They will not be able to login.')"
                       class="block bg-red-50 hover:bg-red-100 text-red-700 px-4 py-3 rounded-lg">
                        <i class="fas fa-ban mr-2"></i>Suspend Account
                    </a>
                    <?php else: ?>
                    <a href="?action=activate&id=<?php echo $user_id; ?>" 
                       onclick="return confirm('Activate this user?')"
                       class="block bg-green-50 hover:bg-green-100 text-green-700 px-4 py-3 rounded-lg">
                        <i class="fas fa-check mr-2"></i>Activate Account
                    </a>
                    <?php endif; ?>
                    
                    <a href="?action=delete&id=<?php echo $user_id; ?>" 
                       onclick="return confirm('WARNING: This will permanently delete the user and all their data. This action cannot be undone.')"
                       class="block bg-red-600 hover:bg-red-700 text-white px-4 py-3 rounded-lg">
                        <i class="fas fa-trash mr-2"></i>Delete User
                    </a>
                </div>
            </div>
            
            <!-- User Information -->
            <div class="bg-white rounded-xl shadow p-6">
                <h4 class="text-lg font-bold mb-4">User Information</h4>
                <div class="space-y-3">
                    <div class="flex justify-between">
                        <span class="text-gray-600">Referral Code:</span>
                        <span class="font-mono"><?php echo $user['referral_code']; ?></span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-600">Referred By:</span>
                        <span><?php echo $user['referred_by'] ? 'User #' . $user['referred_by'] : 'None'; ?></span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-600">Last Login:</span>
                        <span><?php echo $user['last_login'] ? date('M d, H:i', strtotime($user['last_login'])) : 'Never'; ?></span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-600">Last IP:</span>
                        <span><?php echo $user['last_ip'] ?? 'N/A'; ?></span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-600">2FA Enabled:</span>
                        <span><?php echo $user['two_fa_enabled'] ? 'Yes' : 'No'; ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php require_once 'footer.php'; ?>