<?php
session_start();
include('../../includes/config.php');

if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 1) {
    header("Location: ../../index.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: user_management.php");
    exit();
}

$first_name = trim($_POST['first_name'] ?? '');
$last_name = trim($_POST['last_name'] ?? '');
$username = trim($_POST['username'] ?? '');
$email = trim($_POST['email'] ?? '');
$phone = trim($_POST['phone_number'] ?? '');
$role_id = (int)($_POST['role_id'] ?? 0);
$store_id = (int)($_POST['store_id'] ?? 0);
$password = password_hash('123456', PASSWORD_DEFAULT); // default password

// Basic required check
if (!$first_name || !$last_name || !$username || !$email || !$role_id || !$store_id) {
    header("Location: user_management.php?error=Missing required fields.");
    exit();
}

// Uniqueness check
$check = $conn->prepare("SELECT id FROM users WHERE email = ? OR username = ?");
$check->bind_param("ss", $email, $username);
$check->execute();
$check->store_result();
if ($check->num_rows > 0) {
    $check->close();
    header("Location: user_management.php?error=Email or Username already exists.");
    exit();
}
$check->close();

// Insert user
$stmt = $conn->prepare("
    INSERT INTO users (first_name, last_name, username, email, phone_number, role_id, store_id, password, created_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
");

$stmt->bind_param("sssssiis", $first_name, $last_name, $username, $email, $phone, $role_id, $store_id, $password);

if ($stmt->execute()) {
    // Log action
    $newUserId = $stmt->insert_id;
    $userId = $_SESSION['user_id'];
    $roleId = $_SESSION['role_id'];
    $deviceInfo = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';

    $details = json_encode([
        'user_id' => $newUserId,
        'first_name' => $first_name,
        'last_name' => $last_name,
        'username' => $username,
        'email' => $email,
        'phone_number' => $phone,
        'role_id' => $role_id,
        'store_id' => $store_id,
        'default_password' => true
    ]);

    $logStmt = $conn->prepare("
        INSERT INTO audit_log (user_id, role_id, action, details, module, device_info)
        VALUES (?, ?, ?, ?, ?, ?)
    ");
    $action = "Create User";
    $module = "users";
    $logStmt->bind_param("iissss", $userId, $roleId, $action, $details, $module, $deviceInfo);
    $logStmt->execute();
    $logStmt->close();

    header("Location: user_management.php?success=1");
} else {
    $errorMsg = urlencode("Failed to create user. Please try again.");
    header("Location: user_management.php?error=$errorMsg");
}
$stmt->close();
