<?php
require_once 'db.php';

header('Content-Type: application/json');
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

$input = json_decode(file_get_contents('php://input'), true);
$name = $input['name'] ?? '';
$email = $input['email'] ?? '';
$username = $input['username'] ?? '';
$password = $input['password'] ?? '';
$role = $input['role'] ?? 'student';

if (!$name || !$email || !$password || !$username) {
    http_response_code(400);
    echo json_encode(['message' => 'Name, email, username, and password required']);
    exit;
}

// Check if email or username exists
$check = $mysqli->prepare("SELECT id FROM users WHERE email = ? OR username = ?");
$check->bind_param('ss', $email, $username);
$check->execute();
if ($check->get_result()->num_rows > 0) {
    http_response_code(409);
    echo json_encode(['message' => 'Email or Username already registered']);
    exit;
}

$password_hash = password_hash($password, PASSWORD_DEFAULT);
$today = date('Y-m-d');
$streak = 1;

$stmt = $mysqli->prepare("INSERT INTO users (name, email, username, password_hash, role, streak_count, last_login_date) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param('sssssis', $name, $email, $username, $password_hash, $role, $streak, $today);

if ($stmt->execute()) {
    $id = $stmt->insert_id;
    echo json_encode([
        'id' => $id,
        'name' => $name,
        'email' => $email,
        'username' => $username,
        'role' => $role,
        'streak_count' => $streak,
        'last_login_date' => $today
    ]);
} else {
    http_response_code(500);
    echo json_encode(['message' => 'Registration failed: ' . $mysqli->error]);
}
?>
