<?php
class AuthController {
    
    public function login() {
        if (Auth::check()) {
            redirect('?page=dashboard');
        }
        $pageTitle = 'Sign In';
        $layout = 'auth';
        ob_start();
        require APP_PATH . '/views/auth/login.php';
        $content = ob_get_clean();
        require APP_PATH . '/views/layouts/auth.php';
    }

    public function loginPost() {
        CSRF::verify();
        
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';

        // Store old input
        $_SESSION['_old_input'] = ['email' => $email];

        if (empty($email) || empty($password)) {
            flash('error', 'Please enter your email and password.');
            redirect('?page=login');
        }

        // Check lockout
        if (Auth::isLockedOut($email)) {
            flash('error', 'Too many login attempts. Please try again in 15 minutes.');
            redirect('?page=login');
        }

        $db = Database::getInstance();
        $user = $db->fetch(
            "SELECT u.*, r.name as role_name, r.slug as role_slug 
             FROM users u 
             LEFT JOIN roles r ON u.role_id = r.id 
             WHERE u.email = ? AND u.deleted_at IS NULL AND u.status = 'active'",
            [$email]
        );

        if (!$user || !password_verify($password, $user['password'])) {
            Auth::recordFailedAttempt($email);
            flash('error', 'Invalid email or password.');
            redirect('?page=login');
        }

        // Login success
        Auth::login($user);
        
        // Update last login
        $db->update('users', ['last_login_at' => date('Y-m-d H:i:s')], 'id = ?', [$user['id']]);
        
        // Audit log
        auditLog('login', 'users', $user['id'], null, ['ip' => $_SERVER['REMOTE_ADDR'] ?? '']);

        redirect('?page=dashboard');
    }

    public function logout() {
        if (Auth::check()) {
            auditLog('logout', 'users', Auth::user()['id']);
        }
        Auth::logout();
        flash('success', 'You have been signed out.');
        redirect('?page=login');
    }

    public function forgotPassword() {
        if (Auth::check()) {
            redirect('?page=dashboard');
        }
        $pageTitle = 'Forgot Password';
        $layout = 'auth';
        ob_start();
        require APP_PATH . '/views/auth/forgot-password.php';
        $content = ob_get_clean();
        require APP_PATH . '/views/layouts/auth.php';
    }

    public function forgotPasswordPost() {
        CSRF::verify();
        $email = trim($_POST['email'] ?? '');
        
        // Always show success to prevent email enumeration
        flash('success', 'If an account exists with that email, a password reset link has been sent.');
        
        if (!empty($email)) {
            $db = Database::getInstance();
            $user = $db->fetch("SELECT id, email FROM users WHERE email = ? AND deleted_at IS NULL", [$email]);
            
            if ($user) {
                $token = generateToken(64);
                $db->update('users', [
                    'reset_token' => password_hash($token, PASSWORD_DEFAULT),
                    'reset_token_expires' => date('Y-m-d H:i:s', strtotime('+1 hour'))
                ], 'id = ?', [$user['id']]);
                
                // In production, send email with reset link
                // For now, log the token
                auditLog('password_reset_requested', 'users', $user['id']);
            }
        }
        
        redirect('?page=forgot-password');
    }
}
