<?php
session_start();
require_once '../includes/config.php'; // Database connection

// Check if user is logged in as admin
if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

// Check if form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username']);
    $email = filter_var(trim($_POST['email']), FILTER_VALIDATE_EMAIL); // Validate email
    $password = $_POST['password'];
    $role = $_POST['role'];

    // Validate input
    if (empty($username) || empty($email) || empty($password)) {
        header('Location: ../register.php?error=All fields are required.');
        exit;
    }

    if (!$email) {
        header('Location: ../register.php?error=Invalid email format.');
        exit;
    }

    // Validate role
    if (!in_array($role, ['admin', 'officer'])) {
        header('Location: ../register.php?error=Invalid role selected.');
        exit;
    }

    // Hash the password
    $hashed_password = password_hash($password, PASSWORD_BCRYPT);

    try {
        // Prepare SQL query to insert new user
        $stmt = $pdo->prepare("INSERT INTO users (username, email, password, role) VALUES (:username, :email, :password, :role)");
        $stmt->execute([
            'username' => $username,
            'email' => $email,
            'password' => $hashed_password,
            'role' => $role,
        ]);

        // Redirect to success page or dashboard
        header('Location: ../index.php?success=User registered successfully.');
        exit;
    } catch (PDOException $e) {
        error_log($e->getMessage());

        // Handle duplicate usernames or emails
        if ($e->getCode() === 23000) { // Integrity constraint violation
            header('Location: ../register.php?error=Username or email already exists.');
            exit;
        }

        // General database error
        header('Location: ../register.php?error=Database error. Please try again.');
        exit;
    }
} else {
    // Redirect if accessed directly
    header('Location: ../register.php');
    exit;
}