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

class RegisterController {

    public function showRegistrationForm() {
        require_once dirname(__DIR__) . '/../views/register.php';
    }

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

            // Sanitize and set user properties
            $user->username = htmlspecialchars(strip_tags($_POST['username']));
            $user->nama_lengkap = htmlspecialchars(strip_tags($_POST['nama_lengkap']));
            $password = $_POST['password'];
            $password_confirm = $_POST['password_confirm'];

            // Basic validation
            if (empty($user->username) || empty($user->nama_lengkap) || empty($password) || empty($password_confirm)) {
                header("Location: ?page=register&error=empty_fields");
                exit();
            }

            if ($password !== $password_confirm) {
                header("Location: ?page=register&error=password_mismatch");
                exit();
            }

            // Check if username already exists
            if ($user->getByUsername()) {
                header("Location: ?page=register&error=username_exists");
                exit();
            }

            // Hash the password
            $user->password = password_hash($password, PASSWORD_DEFAULT);

            // Default role for new registrations
            $user->role = 'petugas'; // Assuming new registrations are 'petugas' by default

            if ($user->register()) {
                header("Location: ?page=login&message=registration_success");
                exit();
            } else {
                header("Location: ?page=register&error=registration_failed");
                exit();
            }
        }
    }
}