<?php

/**
 * Authentication Controller
 * Handles user login, logout, and authentication
 */
class AuthController {
    
    private $userModel;
    
    public function __construct() {
        $this->userModel = new User();
    }
    
    /**
     * Show login page
     */
    public function login() {
        // If already authenticated, redirect to dashboard
        if (isAuthenticated()) {
            redirect(BASE_URL . '/admin/dashboard');
        }
        
        // Handle POST request (login form submission)
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->processLogin();
            return;
        }
        
        // Show login form
        $this->showLoginForm();
    }
    
    /**
     * Show PWA login page
     */
    public function pwaLogin() {
        // If already authenticated, redirect to PWA home
        if (isAuthenticated()) {
            redirect(BASE_URL . '/home');
        }
        
        // Handle POST request (login form submission)
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->processPwaLogin();
            return;
        }
        
        // Show PWA login form
        $this->showPwaLoginForm();
    }
    
    /**
     * Process login form submission
     */
    private function processLogin() {
        // Get and sanitize input
        $username = sanitize($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';
        
        // Validate input
        if (empty($username) || empty($password)) {
            $this->showLoginForm('Please enter both username and password');
            return;
        }
        
        // Attempt authentication
        $user = $this->userModel->authenticate($username, $password);
        
        if ($user) {
            // Create session
            $user->createSession();
            
            // Log successful login
            logError("User logged in: $username", ['user_id' => $user->id]);
            
            // Redirect to dashboard
            redirect(BASE_URL . '/admin/dashboard');
        } else {
            // Log failed login attempt
            logError("Failed login attempt for username: $username");
            
            // Show error
            $this->showLoginForm('Invalid username or password');
        }
    }
    
    /**
     * Show login form
     * 
     * @param string|null $error Error message to display
     */
    private function showLoginForm($error = null) {
        $pageTitle = 'Login';
        $errorMessage = $error;
        
        require_once APP_PATH . '/views/admin/login.php';
    }
    
    /**
     * Show PWA login form
     * 
     * @param string|null $error Error message to display
     */
    private function showPwaLoginForm($error = null) {
        if ($error) {
            $_SESSION['error'] = $error;
        }
        
        require_once APP_PATH . '/views/pwa/login.php';
    }
    
    /**
     * Process PWA login form submission
     */
    private function processPwaLogin() {
        // Get and sanitize input
        $username = sanitize($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';
        
        // Validate input
        if (empty($username) || empty($password)) {
            $this->showPwaLoginForm('Please enter both username and password');
            return;
        }
        
        // Attempt authentication
        $user = $this->userModel->authenticate($username, $password);
        
        if ($user) {
            // Create session
            $user->createSession();
            
            // Log successful login
            logError("PWA user logged in: $username", ['user_id' => $user->id]);
            
            // Redirect to PWA home
            redirect(BASE_URL . '/home');
        } else {
            // Log failed login attempt
            logError("Failed PWA login attempt for username: $username");
            
            // Show error
            $this->showPwaLoginForm('Invalid username or password');
        }
    }
    
    /**
     * Logout user
     */
    public function logout() {
        if (isAuthenticated()) {
            $userId = getCurrentUserId();
            
            // Destroy session
            $this->userModel->destroySession();
            
            // Log logout
            logError("User logged out", ['user_id' => $userId]);
        }
        
        // Redirect to login page
        redirect(BASE_URL . '/admin/login');
    }
    
    /**
     * Logout PWA user
     */
    public function pwaLogout() {
        if (isAuthenticated()) {
            $userId = getCurrentUserId();
            
            // Destroy session
            $this->userModel->destroySession();
            
            // Log logout
            logError("PWA user logged out", ['user_id' => $userId]);
        }
        
        // Redirect to PWA login page
        redirect(BASE_URL . '/login');
    }
    
    /**
     * Check if user is authenticated (middleware)
     * 
     * @return bool
     */
    public function requireAuth() {
        if (!isAuthenticated()) {
            redirect(BASE_URL . '/admin/login');
            exit;
        }
        
        return true;
    }
    
    /**
     * Get current authenticated user
     * 
     * @return User|null
     */
    public function getCurrentUser() {
        if (!isAuthenticated()) {
            return null;
        }
        
        $userId = getCurrentUserId();
        return $this->userModel->findById($userId);
    }
}
