<?php
header('Content-Type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', 1);

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

$name = isset($_POST['name']) ? trim($_POST['name']) : '';
$password = isset($_POST['password']) ? trim($_POST['password']) : '';
$email = isset($_POST['email']) ? trim($_POST['email']) : '';
$age = isset($_POST['age']) ? trim($_POST['age']) : '';
$phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
$gender = isset($_POST['gender']) ? trim($_POST['gender']) : '';
$user_type = isset($_POST['user_type']) ? trim($_POST['user_type']) : 'user'; // 'user' or 'admin'

if ($name === '' || $password === '' || $email === '' || $age === '' || $phone === '' || $gender === '') {
    echo json_encode(['success' => false, 'message' => 'Please fill in all fields']);
    exit;
}

// Validate password strength
if (strlen($password) < 8) {
    echo json_encode(['success' => false, 'message' => 'Password must be at least 8 characters long']);
    exit;
}
if (!preg_match('/[a-zA-Z]/', $password)) {
    echo json_encode(['success' => false, 'message' => 'Password must contain at least one letter']);
    exit;
}
if (!preg_match('/[0-9]/', $password)) {
    echo json_encode(['success' => false, 'message' => 'Password must contain at least one number']);
    exit;
}
if (!preg_match('/[!@#$%^&*()_+\-=\[\]{};:\'",.<>?\/\\|`~]/', $password)) {
    echo json_encode(['success' => false, 'message' => 'Password must contain at least one special character (!@#$%^&* etc)']);
    exit;
}

require __DIR__ . '/db_config.php';

// Check for conflicts
// Check for existing username/email/phone in `users`
$checkStmt = $conn->prepare("SELECT `username`,`email`,`phone` FROM `users` WHERE `username` = ? OR `email` = ? OR `phone` = ?");
if (!$checkStmt) {
    echo json_encode(['success' => false, 'message' => 'DB prepare error']);
    exit;
}
$checkStmt->bind_param('sss', $name, $email, $phone);
$checkStmt->execute();
$res = $checkStmt->get_result();

$conflicts = [];
while ($row = $res->fetch_assoc()) {
    if (strcasecmp($row['name'], $name) === 0) $conflicts[] = 'name';
    if (strcasecmp($row['email'], $email) === 0) $conflicts[] = 'email';
    if (strcasecmp($row['phone'], $phone) === 0) $conflicts[] = 'phone';
}
$checkStmt->close();

if (!empty($conflicts)) {
    echo json_encode(['success' => false, 'message' => 'conflict', 'conflicts' => array_values(array_unique($conflicts))]);
    $conn->close();
    exit;
}

// Insert user
$ageInt = (int)$age;
// Insert into users table (store password hash)
$pwHash = password_hash($password, PASSWORD_DEFAULT);
// If configured for plaintext storage (dev only), store raw password instead of hash
if (isset($STORE_PLAINTEXT_PASSWORDS) && $STORE_PLAINTEXT_PASSWORDS === true) {
    $storePassword = $password;
} else {
    $storePassword = $pwHash;
}

$insertStmt = $conn->prepare("INSERT INTO `users` (`username`,`email`,`password_hash`,`age`,`phone`,`gender`,`status`,`created_at`) VALUES (?, ?, ?, ?, ?, ?, 'active', NOW())");
if (!$insertStmt) {
    echo json_encode(['success' => false, 'message' => 'DB prepare error']);
    $conn->close();
    exit;
}
$insertStmt->bind_param('sssiis', $name, $email, $storePassword, $ageInt, $phone, $gender);
$executed = $insertStmt->execute();
if ($executed) {
    $insertId = $conn->insert_id;
    // Admin signup via the public form is disabled for security. Admins should be created/promoted
    // manually via the database or by an existing admin through the admin UI.
    echo json_encode(['success' => true, 'redirect' => 'dashboard.php', 'id' => $insertId]);
} else {
    echo json_encode(['success' => false, 'message' => 'insert_failed', 'error' => $insertStmt->error]);
}
$insertStmt->close();
$conn->close();
