<?php
require_once dirname(__DIR__) . '/models/User.php';
require_once dirname(__DIR__) . '/../config/db.php';

class LoginController {
    
    public function showLoginForm() {
        require_once dirname(__DIR__) . '/../views/login.php';
    }

    public function login() {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $db = connectDB();
            $user = new User($db);

            $user->username = $_POST['username'];
            
            if ($user->getByUsername() && password_verify($_POST['password'], $user->password ?? '')) {
                // Password is correct, start session
                // session_start(); is already called in index.php
                $_SESSION['user_id'] = $user->id_user;
                $_SESSION['username'] = $user->username;
                $_SESSION['nama_lengkap'] = $user->nama_lengkap;
                $_SESSION['role'] = $user->role;
                
                // Redirect to home page
                header("Location: ?page=home");
                exit();
            } else {
                // Login failed
                header("Location: ?page=login&error=1");
                exit();
            }
        }
    }
    
    public function logout() {
        // session_start(); is already called in index.php
        // Unset all of the session variables
        $_SESSION = array();

        // Destroy the session
        session_destroy();

        // Redirect to login page
        header("location: ?page=login");
        exit;
    }
}