<?php
/**
 * Auth Class - WeaverSM
 */
class Auth {
    private $pdo;
    private $user;
    
    public function __construct() {
        $this->pdo = getDBConnection();
        $this->user = new User();
    }
    
    public function register($name, $email, $password, $confirmPassword) {
        $name = sanitize($name);
        $email = sanitizeEmail($email);
        
        if (empty($name) || strlen($name) < 2) {
            return ['success' => false, 'message' => 'Name must be at least 2 characters'];
        }
        if (!isValidEmail($email)) {
            return ['success' => false, 'message' => 'Invalid email address'];
        }
        if ($password !== $confirmPassword) {
            return ['success' => false, 'message' => 'Passwords do not match'];
        }
        
        $passwordCheck = isStrongPassword($password);
        if (!$passwordCheck['valid']) {
            return ['success' => false, 'message' => $passwordCheck['message']];
        }
        if ($this->user->emailExists($email)) {
            return ['success' => false, 'message' => 'Email already registered'];
        }
        
        $result = $this->user->create([
            'name' => $name, 
            'email' => $email, 
            'password' => $password, 
            'role' => 'user', 
            'status' => 'active'
        ]);
        
        if ($result['success']) {
            logActivity($result['user_id'], 'register', 'New user registration');
        }
        
        return $result;
    }
    
    public function login($email, $password) {
        $email = sanitizeEmail($email);
        
        if (!isValidEmail($email)) {
            return ['success' => false, 'message' => 'Invalid email address'];
        }
        if (!checkLoginAttempts($email)) {
            return ['success' => false, 'message' => 'Too many attempts. Try again in ' . LOCKOUT_DURATION . ' minutes'];
        }
        
        $user = $this->user->getByEmail($email);
        
        if (!$user || !verifyPassword($password, $user['password'])) {
            recordLoginAttempt($email);
            return ['success' => false, 'message' => 'Invalid email or password'];
        }
        
        if ($user['status'] === 'suspended') {
            return ['success' => false, 'message' => 'Account suspended'];
        }
        if ($user['status'] === 'banned') {
            return ['success' => false, 'message' => 'Account banned'];
        }
        
        clearLoginAttempts($email);
        regenerateSession();
        
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['email'] = $user['email'];
        $_SESSION['name'] = $user['name'];
        $_SESSION['role'] = $user['role'];
        $_SESSION['balance'] = (float)$user['balance'];
        $_SESSION['last_activity'] = time();
        
        if ($user['role'] === 'assistant') {
            $_SESSION['permissions'] = $this->user->getAssistantPermissions($user['id']) ?: [];
        }
        
        logActivity($user['id'], 'login', 'User logged in');
        
        $redirect = SITE_URL . '/user/dashboard.php';
        if ($user['role'] === 'admin' || $user['role'] === 'assistant') {
            $redirect = SITE_URL . '/admin/dashboard.php';
        }
        
        return ['success' => true, 'message' => 'Login successful', 'redirect' => $redirect];
    }
    
    public function logout() {
        $userId = getCurrentUserId();
        if ($userId) {
            logActivity($userId, 'logout', 'User logged out');
        }
        
        $_SESSION = [];
        
        if (ini_get("session.use_cookies")) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
        }
        
        session_destroy();
        return ['success' => true, 'message' => 'Logged out successfully'];
    }
    
    public function refreshBalance($userId) {
        $balance = $this->user->getBalance($userId);
        $_SESSION['balance'] = $balance;
        return $balance;
    }
}
