<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Models\User;

class AuthController extends Controller {
    
    public function showLogin() {
        if ($this->isAuthenticated()) {
            $this->redirect('/dashboard');
        }
        
        $this->render('auth/login', [
            'title' => 'Login',
            'csrf_token' => $this->csrf_token()
        ]);
    }
    
    public function login() {
        // Verify CSRF token
        if (!isset($_POST['csrf_token']) || !\Security::validateCSRFToken($_POST['csrf_token'])) {
            die('Invalid CSRF token');
        }
        
        $username = $_POST['username'] ?? '';
        $password = $_POST['password'] ?? '';
        
        if (empty($username) || empty($password)) {
            $this->render('auth/login', [
                'title' => 'Login',
                'error' => 'Please enter username and password',
                'csrf_token' => $this->csrf_token()
            ]);
            return;
        }
        
        $userModel = new User();
        $user = $userModel->authenticate($username, $password);
        
        if ($user) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['full_name'] = $user['full_name'];
            $_SESSION['role'] = $user['role'];
            
            $userModel->updateLastLogin($user['id'], $_SERVER['REMOTE_ADDR']);
            
            $this->redirect('/dashboard');
        } else {
            $this->render('auth/login', [
                'title' => 'Login',
                'error' => 'Invalid username or password',
                'csrf_token' => $this->csrf_token()
            ]);
        }
    }
    
    public function logout() {
        session_destroy();
        $this->redirect('/login');
    }
}