<?php
// controllers/AuthController.php

class AuthController {
    public function login() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $username = trim($_POST['username'] ?? '');
            $password = $_POST['password'] ?? '';
            $error = '';

            if (empty($username) || empty($password)) {
                $error = 'Please enter both username and password.';
            } else {
                $db = Database::getConnection();
                $stmt = $db->prepare('SELECT id, tenant_id, password_hash, role FROM users WHERE username = ?');
                $stmt->execute([$username]);
                $user = $stmt->fetch();

                if ($user && password_verify($password, $user['password_hash'])) {
                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['tenant_id'] = $user['tenant_id'];
                    $_SESSION['role'] = $user['role'];
                    $_SESSION['username'] = $username;
                    
                    header('Location: /dashboard');
                    exit;
                } else {
                    $error = 'Invalid username or password.';
                }
            }
            
            require 'views/auth/login.php';
        }
    }
}
