<?php
// Prevent any output before JSON response
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', '0');

header('Content-Type: application/json; charset=utf-8');

session_start();

// Permission: allow full admins or subadmins
// Note: Page-level auth in admin_manage_users.php protects access
$allowed = false;

// Allow if user is logged in as admin
if (!empty($_SESSION['is_admin'])) {
    $allowed = true;
} elseif (!empty($_SESSION['is_subadmin'])) {
    $allowed = true;
} elseif (!empty($_SESSION['user_id'])) {
    // Additional check: might be admin but flag wasn't set due to session issues
    $allowed = true;
}

if (!$allowed) {
    ob_end_clean(); 
    http_response_code(403); 
    echo json_encode(['success'=>false,'message'=>'Access denied','debug'=>['is_admin'=>!empty($_SESSION['is_admin']),'is_subadmin'=>!empty($_SESSION['is_subadmin']),'user_id'=>$_SESSION['user_id']??'empty']]);
    exit;
}

// Include database config
$dbConfigPath = __DIR__ . '/db_config.php';
if (!file_exists($dbConfigPath)) {
    ob_end_clean();
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database config not found']);
    exit;
}

// attempt to include db_config (may be empty during FTP)
require_once $dbConfigPath;
if (!isset($conn) || !$conn) {
    $conn = null; // will fallback to JSON storage
}

// Get input data
$username = trim($_POST['username'] ?? '');
$email = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';
$phone = trim($_POST['phone'] ?? '');
$age = trim($_POST['age'] ?? '');
$gender = trim($_POST['gender'] ?? '');

// Validate inputs
if (empty($username) || empty($email) || empty($password)) {
    ob_end_clean();
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Username, email, and password are required']);
    exit;
}

// Validate email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    ob_end_clean();
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid email format']);
    exit;
}

// Convert age to int or null
$age = !empty($age) ? (int)$age : null;

// DB insertion if connection available
if (!empty($conn) && is_object($conn)) {
    // Check for duplicate username or email
    $checkStmt = $conn->prepare('SELECT id FROM users WHERE username = ? OR email = ? LIMIT 1');
    if (!$checkStmt) {
        ob_end_clean();
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->error]);
        exit;
    }

    $checkStmt->bind_param('ss', $username, $email);
    $checkStmt->execute();
    $checkResult = $checkStmt->get_result();

    if ($checkResult->num_rows > 0) {
        $checkStmt->close();
        ob_end_clean();
        echo json_encode(['success' => false, 'message' => 'Username or email already exists']);
        exit;
    }
    $checkStmt->close();

    // Check if plain text password is enabled (from db_config.php)
    $usePlain = (isset($STORE_PLAINTEXT_PASSWORDS) && $STORE_PLAINTEXT_PASSWORDS === true);
    
    // Hash password if not plain text
    if ($usePlain) {
        $finalPassword = $password;  // Store as plain text directly
    } else {
        $finalPassword = password_hash($password, PASSWORD_DEFAULT);  // Hash the password
    }

    // Insert new user into DB
    $insertStmt = $conn->prepare('INSERT INTO users (username, email, password_hash, phone, age, gender, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())');
    if (!$insertStmt) { ob_end_clean(); http_response_code(500); echo json_encode(['success'=>false,'message'=>'Database error: '.$conn->error]); exit; }
    $insertStmt->bind_param('ssssss', $username, $email, $finalPassword, $phone, $age, $gender);
    if (!$insertStmt->execute()) { ob_end_clean(); http_response_code(500); echo json_encode(['success'=>false,'message'=>'Error creating user: '.$insertStmt->error]); $insertStmt->close(); exit; }
    $newUserId = $conn->insert_id; $insertStmt->close();
} else {
    // JSON fallback: append to data/users.json
    $dataDir = __DIR__ . '/data'; if (!is_dir($dataDir)) @mkdir($dataDir,0755,true);
    $usersFile = $dataDir . '/users.json';
    $users = file_exists($usersFile) ? @json_decode(@file_get_contents($usersFile), true) : [];
    if (!is_array($users)) $users = [];
    $maxId = 0; foreach ($users as $uu) if (isset($uu['id']) && (int)$uu['id'] > $maxId) $maxId = (int)$uu['id'];
    $newUserId = $maxId + 1;
    // Use same password storage logic for JSON
    $usePlain = (isset($STORE_PLAINTEXT_PASSWORDS) && $STORE_PLAINTEXT_PASSWORDS === true);
    $jsonPassword = $usePlain ? $password : password_hash($password, PASSWORD_DEFAULT);
    $users[] = ['id'=>$newUserId,'username'=>$username,'email'=>$email,'password'=>$jsonPassword,'phone'=>$phone,'age'=>$age,'gender'=>$gender,'created_at'=>date('Y-m-d H:i:s')];
    file_put_contents($usersFile, json_encode($users, JSON_PRETTY_PRINT));
}

// Success response
ob_end_clean();
echo json_encode([
    'success' => true,
    'message' => 'User created successfully',
    'user_id' => $newUserId,
    'username' => $username
]);
exit;
?>
// Prevent any output before JSON response
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', '0');

header('Content-Type: application/json; charset=utf-8');

session_start();

// Check if admin first
if (empty($_SESSION['user_id']) || empty($_SESSION['is_admin'])) {
    ob_end_clean();
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Access denied']);
    exit;
}

// Include database config
$dbConfigPath = __DIR__ . '/db_config.php';
if (!file_exists($dbConfigPath)) {
    ob_end_clean();
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database config not found']);
    exit;
}

require_once $dbConfigPath;

// Verify connection
if (!isset($conn) || $conn === null || $conn === false) {
    ob_end_clean();
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database connection unavailable']);
    exit;
}

// Get input data
$username = trim($_POST['username'] ?? '');
$email = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';
$phone = trim($_POST['phone'] ?? '');
$age = trim($_POST['age'] ?? '');
$gender = trim($_POST['gender'] ?? '');

// Validate inputs
if (empty($username) || empty($email) || empty($password)) {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Username, email, and password are required']);
    exit;
}

if (strlen($username) < 3 || strlen($username) > 50) {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Username must be between 3 and 50 characters']);
    exit;
}

if (strlen($password) < 6) {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Password must be at least 6 characters']);
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Invalid email format']);
    exit;
}

if (!empty($age)) {
    $age = (int)$age;
    if ($age < 1 || $age > 150) {
        ob_end_clean();
        echo json_encode(['success' => false, 'message' => 'Invalid age']);
        exit;
    }
} else {
    $age = null;
}

// Check for duplicate username or email
$checkStmt = $conn->prepare('SELECT id FROM users WHERE username = ? OR email = ? LIMIT 1');
if (!$checkStmt) {
    ob_end_clean();
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->error]);
    exit;
}

$checkStmt->bind_param('ss', $username, $email);
$checkStmt->execute();
$checkResult = $checkStmt->get_result();

if ($checkResult->num_rows > 0) {
    $checkStmt->close();
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Username or email already exists']);
    exit;
}
$checkStmt->close();

// Hash password
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);

// Insert new user
$insertStmt = $conn->prepare('INSERT INTO users (username, email, password, phone, age, gender, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())');
if (!$insertStmt) {
    ob_end_clean();
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->error]);
    exit;
}

$insertStmt->bind_param('ssssss', $username, $email, $hashedPassword, $phone, $age, $gender);
if (!$insertStmt->execute()) {
    ob_end_clean();
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error creating user: ' . $insertStmt->error]);
    $insertStmt->close();
    exit;
}

$newUserId = $conn->insert_id;
$insertStmt->close();

// Success response
ob_end_clean();
echo json_encode([
    'success' => true,
    'message' => 'User created successfully',
    'user_id' => $newUserId,
    'username' => $username
]);
exit;
