<?php
class LoginController extends Controller {
    public function index() {
        $this->view('auth/login');
    }

    public function login() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $email = $_POST['email'];
            $password = $_POST['password'];

            $userModel = $this->model('User');
            $user = $userModel->getUserByEmail($email);

            if ($user && hash('sha256', $password) === $user['password']) {
                session_start();
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['user_role'] = $user['role'];
                $_SESSION['user_name'] = $user['name'];

                // Redirect based on role
                if ($user['role'] === 'admin') {
                    header("Location: " . BASE_URL . "/DashboardController/admin");

                } else {
                    header("Location: " . BASE_URL . "/DashboardController/agent");

                }
                exit;
            } else {
                $this->view('auth/login', ['error' => 'Invalid email or password']);
            }
        }
    }

    public function logout() {
        session_start();
        session_destroy();
        header("Location: " . BASE_URL . "/LoginController/index");
    }
}
