<?php
include '../db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    $roleId = (int)$_POST['role_id'];
    $pin = trim($_POST['pin'] ?? '');
    $pin_required_for_void = isset($_POST['pin_required_for_void']) ? 1 : 0;

    // Validation
    $errors = [];
    
    if (empty($username) || empty($email) || empty($password) || empty($roleId)) {
        $errors[] = "All required fields must be filled.";
    }
    
    if ($password !== $confirm_password) {
        $errors[] = "Passwords do not match.";
    }
    
    if (strlen($password) < 6) {
        $errors[] = "Password must be at least 6 characters long.";
    }
    
    // Check if username or email already exists
    $check_stmt = $conn->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
    $check_stmt->bind_param("ss", $username, $email);
    $check_stmt->execute();
    $check_result = $check_stmt->get_result();
    
    if ($check_result->num_rows > 0) {
        $errors[] = "Username or email already exists.";
    }
    
    // Check if role exists
    $role_check = $conn->query("SELECT id FROM roles WHERE id = $roleId");
    if ($role_check->num_rows === 0) {
        $errors[] = "Selected role does not exist.";
    }
    
    if (empty($errors)) {
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        
        $stmt = $conn->prepare("INSERT INTO users (username, email, password, role_id, pin, pin_required_for_void, is_active, created_at) VALUES (?, ?, ?, ?, ?, ?, 1, NOW())");
        $stmt->bind_param("sssisi", $username, $email, $hashed_password, $roleId, $pin, $pin_required_for_void);
        
        if ($stmt->execute()) {
            header("Location: ../users.php?success=user_created");
            exit();
        } else {
            $errors[] = "Failed to create user. Please try again.";
        }
    }
    
    // If there are errors, redirect back with error message
    if (!empty($errors)) {
        $error_message = implode(" ", $errors);
        header("Location: ../users.php?error=" . urlencode($error_message));
        exit();
    }
}

header("Location: ../users.php");
exit();
?>
