<?php
class LoginController extends Controller {

    public function index() {
        $data['title'] = "Admin Login";
        $this->view('login', $data);
    }

    public function submit() {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }

        $username = $_POST['username'] ?? '';
        $password = $_POST['password'] ?? '';

        $userModel = $this->model('User');
        $user = $userModel->login($username, $password);

        if ($user) {
            $_SESSION['admin_logged_in'] = true;
            $_SESSION['admin_username'] = $user['username'];
            header('Location: ' . BASE_URL . '/dashboard');
            exit;
        } else {
            $data['title'] = "Admin Login";
            $data['error'] = "Invalid Username or Password!";
            $this->view('login', $data);
        }
    }

    public function logout() {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }

        session_destroy();
        header('Location: ' . BASE_URL . '/login');
        exit;
    }
}
