<?php
include 'layouts/session.php';
include 'layouts/dbconn.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Debug logging
    error_log("POST data received: " . print_r($_POST, true));
    
    $username = $_POST['username'];
    $email = $_POST['email'];
    $full_name = $_POST['full_name'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $role_id = $_POST['role_id'];

    // Validate role_id
    if (empty($role_id)) {
        $_SESSION['error_msg'] = "Role ID is required";
        header("Location: add_user.php");
        exit();
    }
    
    try {
        $conn->begin_transaction();

        // Log role query
        error_log("Fetching role for ID: " . $role_id);
        
        // Get the role name
        $stmt = $conn->prepare("SELECT role_name FROM user_role WHERE role_id = ?");
        $stmt->bind_param("i", $role_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 0) {
            throw new Exception("Invalid role ID");
        }
        
        $role = $result->fetch_assoc();
        $user_role = strtolower(str_replace(' ', '_', $role['role_name']));
        
        error_log("Role name fetched: " . $user_role);

        // Insert user with explicit role_id
        $stmt = $conn->prepare("INSERT INTO users (username, email, full_name, password, user_role, role_id) 
                               VALUES (?, ?, ?, ?, ?, ?)");
                               
        if (!$stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        
        $stmt->bind_param("sssssi", $username, $email, $full_name, $password, $user_role, $role_id);
        
        if (!$stmt->execute()) {
            throw new Exception("User insert failed: " . $stmt->error);
        }
        
        $user_id = $conn->insert_id;
        error_log("New user ID: " . $user_id);
        
        // Insert into user_roles
        $role_stmt = $conn->prepare("INSERT INTO user_roles (user_id, role_id) VALUES (?, ?)");
        
        if (!$role_stmt) {
            throw new Exception("Role mapping prepare failed: " . $conn->error);
        }
        
        $role_stmt->bind_param("ii", $user_id, $role_id);
        
        if (!$role_stmt->execute()) {
            throw new Exception("Role mapping failed: " . $role_stmt->error);
        }
        
        $conn->commit();
        $_SESSION['success_msg'] = "User created successfully";
        error_log("User created successfully with role_id: " . $role_id);
        
    } catch (Exception $e) {
        $conn->rollback();
        error_log("Error in save_user.php: " . $e->getMessage());
        $_SESSION['error_msg'] = "Error: " . $e->getMessage();
    } finally {
        if (isset($stmt)) $stmt->close();
        if (isset($role_stmt)) $role_stmt->close();
    }
    
    header("Location: all_users.php");
    exit();
}
?>