<?php
session_start();
require_once 'includes/auth.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get and sanitize input
    $fullName = trim($_POST['full_name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = filter_var(trim($_POST['email'] ?? ''), FILTER_VALIDATE_EMAIL);
    $password = $_POST['password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';
    $ageRange = $_POST['age_range'] ?? null;
    $gender = $_POST['gender'] ?? null;
    $ethnicity = !empty($_POST['ethnicity']) ? trim($_POST['ethnicity']) : null;
    
    // Basic validation
    $errors = [];
    if (empty($fullName)) $errors[] = 'Full name is required';
    if (empty($phone) || !preg_match('/^[0-9]+$/', $phone)) $errors[] = 'Valid phone number is required';
    if (!$email) $errors[] = 'Valid email is required';
    if (strlen($password) < 6) $errors[] = 'Password must be at least 6 characters';
    if ($password !== $confirmPassword) $errors[] = 'Passwords do not match';
    if (empty($ageRange)) $errors[] = 'Age range is required';
    if (empty($gender)) $errors[] = 'Gender is required';
    
    if (!empty($errors)) {
        header('Location: login.php?register=1&error=' . urlencode(implode('; ', $errors)));
        exit();
    }
    
    try {
        $pdo = getDBConnection();
        
        // Check if phone or email already exists
        $stmt = $pdo->prepare("SELECT id FROM users WHERE phone = ? OR email = ?");
        $stmt->execute([$phone, $email]);
        if ($stmt->fetch()) {
            throw new Exception('Phone number or email already registered');
        }
        
        // Hash password
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
        
        // Start transaction
        $pdo->beginTransaction();
        
        // Insert user
        $stmt = $pdo->prepare("
            INSERT INTO users 
            (full_name, phone, email, password_hash, age_range, gender, ethnicity, created_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
        ");
        
        $stmt->execute([
            $fullName,
            $phone,
            $email,
            $hashedPassword,
            $ageRange,
            $gender,
            $ethnicity
        ]);
        
        $userId = $pdo->lastInsertId();
        
        // Initialize user stats
        $stmt = $pdo->prepare("
            INSERT INTO user_stats 
            (user_id, points, last_participation) 
            VALUES (?, 0, CURDATE())
        ");
        $stmt->execute([$userId]);
        
        $pdo->commit();
        
        // Set session and redirect
        $_SESSION['user_id'] = $userId;
        $_SESSION['phone'] = $phone;
        header('Location: chat.php');
        exit();
        
    } catch (Exception $e) {
        if (isset($pdo) && $pdo->inTransaction()) {
            $pdo->rollBack();
        }
        error_log('Registration error: ' . $e->getMessage());
        header('Location: login.php?register=1&error=' . urlencode($e->getMessage()));
        exit();
    }
    
} else {
    header('Location: login.php');
    exit();
}
