<?php
require_once '../config/cors.php';
require_once '../config/database.php';
require_once '../utils/helpers.php';

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

// Extract authorization token
$token = getAuthToken();

// Validate token
$user = getUserFromToken($token);
if (!$user) {
    errorResponse('User not authenticated', 401);
}

// Check if user is admin
if (!isAdmin($user['id'])) {
    errorResponse('Unauthorized: Admin access required', 403);
}

// Validate action
validateInput($input, ['action']);

$action = $input['action'];

try {
    switch ($action) {
        case 'list':
            // Get all users with their profiles
            $stmt = $pdo->prepare("SELECT u.id, u.email, u.created_at, u.first_name, u.last_name, u.is_approved, u.email_verified, p.role_id, ur.name as role, up.username, up.phone FROM users u LEFT JOIN profiles p ON u.id = p.user_id LEFT JOIN user_roles ur ON p.role_id = ur.id LEFT JOIN user_profiles up ON u.id = up.user_id ORDER BY u.created_at DESC");
            $stmt->execute();
            $users = $stmt->fetchAll();
            
            jsonResponse(['users' => $users], 200);
            break;
            
        case 'create':
            $userData = isset($input['userData']) ? $input['userData'] : null;
            
            validateInput($userData, ['email', 'password']);
            
            // Check if user already exists
            $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$userData['email']]);
            if ($stmt->fetch()) {
                errorResponse('User with this email already exists', 400);
            }
            
            // Create user
            $userId = generateUUID();
            $passwordHash = password_hash($userData['password'], PASSWORD_DEFAULT);
            
            $stmt = $pdo->prepare("INSERT INTO users (id, email, password_hash, first_name, last_name) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([
                $userId,
                $userData['email'],
                $passwordHash,
                isset($userData['firstName']) ? $userData['firstName'] : null,
                isset($userData['lastName']) ? $userData['lastName'] : null
            ]);
            
            // Create profile
            $roleId = isset($userData['role']) && $userData['role'] === 'admin' ? 1 : 2; // 1 = admin, 2 = user
            $profileId = generateUUID();
            $stmt = $pdo->prepare("INSERT INTO profiles (id, user_id, first_name, last_name, role_id) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([
                $profileId,
                $userId,
                isset($userData['firstName']) ? $userData['firstName'] : null,
                isset($userData['lastName']) ? $userData['lastName'] : null,
                $roleId
            ]);
            
            // Create user progress
            $progressId = generateUUID();
            $stmt = $pdo->prepare("INSERT INTO user_progress (id, user_id) VALUES (?, ?)");
            $stmt->execute([$progressId, $userId]);
            
            // Create user profile
            $userProfileId = generateUUID();
            $baseUsername = isset($userData['firstName']) ? strtolower(str_replace(' ', '', $userData['firstName'])) : explode('@', $userData['email'])[0];
            $username = $baseUsername;
            
            // Ensure username uniqueness
            $stmt = $pdo->prepare("SELECT id FROM user_profiles WHERE username = ?");
            $stmt->execute([$username]);
            if ($stmt->fetch()) {
                $username = $baseUsername . '_' . bin2hex(random_bytes(2));
            }

            $stmt = $pdo->prepare("INSERT INTO user_profiles (id, user_id, first_name, last_name, username, role) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([
                $userProfileId,
                $userId,
                isset($userData['firstName']) ? $userData['firstName'] : null,
                isset($userData['lastName']) ? $userData['lastName'] : null,
                $username,
                $userData['role'] ?? 'user'
            ]);
            
            jsonResponse([
                'success' => true,
                'email' => $userData['email']
            ], 200);
            break;
            
        case 'update':
            $userId = isset($input['userId']) ? $input['userId'] : null;
            $userData = isset($input['userData']) ? $input['userData'] : null;
            
            validateInput($input, ['userId', 'userData']);
            
            // Update profile
            $roleId = isset($userData['role']) && $userData['role'] === 'admin' ? 1 : 2; // 1 = admin, 2 = user
            $stmt = $pdo->prepare("UPDATE profiles SET first_name = ?, last_name = ?, role_id = ? WHERE user_id = ?");
            $stmt->execute([
                isset($userData['firstName']) ? $userData['firstName'] : null,
                isset($userData['lastName']) ? $userData['lastName'] : null,
                $roleId,
                $userId
            ]);
            
            // Update user_profiles table as well
            $stmt = $pdo->prepare("UPDATE user_profiles SET first_name = ?, last_name = ? WHERE user_id = ?");
            $stmt->execute([
                isset($userData['firstName']) ? $userData['firstName'] : null,
                isset($userData['lastName']) ? $userData['lastName'] : null,
                $userId
            ]);

            // Sync with users table
            $stmt = $pdo->prepare("UPDATE users SET first_name = ?, last_name = ? WHERE id = ?");
            $stmt->execute([
                isset($userData['firstName']) ? $userData['firstName'] : null,
                isset($userData['lastName']) ? $userData['lastName'] : null,
                $userId
            ]);
            
            jsonResponse(['success' => true], 200);
            break;
            
        case 'delete':
            $userId = isset($input['userId']) ? $input['userId'] : null;
            
            validateInput($input, ['userId']);
            
            // Delete user (cascades to related tables)
            $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
            $stmt->execute([$userId]);
            
            jsonResponse(['success' => true], 200);
            break;

        case 'approve_user':
            $userId = isset($input['userId']) ? $input['userId'] : null;
            validateInput($input, ['userId']);

            $stmt = $pdo->prepare("UPDATE users SET is_approved = 1 WHERE id = ?");
            $stmt->execute([$userId]);

            // Also verify email if requested? Optional. 
            // For now just approve.

            jsonResponse(['success' => true], 200);
            break;


        case 'login_as_user':
            $userId = isset($input['userId']) ? $input['userId'] : null;

            validateInput($input, ['userId']);

            // Get target user details
            $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
            $stmt->execute([$userId]);
            $targetUser = $stmt->fetch();

            if (!$targetUser) {
                errorResponse('User not found', 404);
            }

            // Create new session for this user
            $sessionToken = createSession($userId);

            // Fetch profile role info
            $stmt = $pdo->prepare("SELECT r.name as role FROM profiles p JOIN user_roles r ON p.role_id = r.id WHERE p.user_id = ?");
            $stmt->execute([$userId]);
            $profile = $stmt->fetch();

            jsonResponse([
                'success' => true,
                'user' => [
                    'id' => $targetUser['id'],
                    'email' => $targetUser['email'],
                    'first_name' => $targetUser['first_name'],
                    'last_name' => $targetUser['last_name']
                ],
                'profile' => $profile,
                'session_token' => $sessionToken
            ], 200);
            break;
            
        default:
            errorResponse('Invalid action', 400);
    }
} catch (Exception $e) {
    errorResponse('Error managing users: ' . $e->getMessage(), 500);
}
?>