<?php

require_once '../app/Models/User.php';

class AuthController
{
    private $userModel;
    
    public function __construct()
    {
        $this->userModel = new User();
    }
    
    public function showLogin()
    {
        // If already logged in, redirect to dashboard
        if (isset($_SESSION['user_id'])) {
            header('Location: /samanta_crm/dashboard');
            exit;
        }
        
        $this->view('login');
    }
    
    public function login()
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            header('Location: /samanta_crm/login');
            exit;
        }
        
        $email = $_POST['email'] ?? '';
        $password = $_POST['password'] ?? '';
        
        if (empty($email) || empty($password)) {
            $_SESSION['error'] = 'Email and password are required';
            header('Location: /samanta_crm/login');
            exit;
        }
        
        $user = $this->userModel->findByEmail($email);
        
        if ($user && $this->userModel->verifyPassword($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_name'] = $user['name'];
            $_SESSION['user_role'] = $user['role'];
            $_SESSION['user_type_id'] = $user['user_type_id'];
            $_SESSION['language'] = $user['language'] ?? 'pl'; // Set user's language or default to Polish
            
            header('Location: /samanta_crm/dashboard');
            exit;
        }
        
        $_SESSION['error'] = 'Invalid email or password';
        header('Location: /samanta_crm/login');
        exit;
    }
    
    public function logout()
    {
        session_destroy();
        header('Location: /samanta_crm/login');
        exit;
    }
    
    private function view($view, $data = [])
    {
        extract($data);
        require_once "../app/Views/{$view}.php";
    }
}
