<?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() {
        try {
            $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->add()) {
                header("Location: ?page=login&message=registration_success");
                exit();
            } else {
                header("Location: ?page=register&error=registration_failed_no_exception");
                exit();
            }
        } catch (PDOException $e) {
            // Redirect with a detailed error message for debugging
            $errorMessage = urlencode("DB Error: " . $e->getMessage());
            header("Location: ?page=register&error=" . $errorMessage);
            exit();
        }
    }
}