<?php
/**
 * AJAX: User Registration (Simplified)
 */
header('Content-Type: application/json; charset=utf-8');

try {
    // Initialize
    define('BASE_PATH', dirname(dirname(dirname(__DIR__))));
    require_once BASE_PATH . '/app/config/config.php';
    
    // Start session
    if (session_status() === PHP_SESSION_NONE) {
        session_name(SESSION_NAME);
        session_start();
    }
    
    // Must be POST
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['success' => false, 'message' => 'Invalid request']);
        exit;
    }
    
    // Get and validate data
    $fullName = trim($_POST['full_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $password = $_POST['password'] ?? '';
    $passwordConfirm = $_POST['password_confirmation'] ?? '';
    
    $errors = [];
    
    if (empty($fullName) || strlen($fullName) < 3) {
        $errors['full_name'] = 'নাম কমপক্ষে ৩ অক্ষর হতে হবে';
    }
    
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors['email'] = 'সঠিক ইমেইল দিন';
    }
    
    if (empty($phone) || !preg_match('/^01[3-9]\d{8}$/', $phone)) {
        $errors['phone'] = 'সঠিক মোবাইল নম্বর দিন (01XXXXXXXXX)';
    }
    
    if (empty($password) || strlen($password) < 6) {
        $errors['password'] = 'পাসওয়ার্ড কমপক্ষে ৬ অক্ষর হতে হবে';
    }
    
    if ($password !== $passwordConfirm) {
        $errors['password_confirmation'] = 'পাসওয়ার্ড মিলছে না';
    }
    
    if (!empty($errors)) {
        echo json_encode(['success' => false, 'message' => 'তথ্য সঠিকভাবে পূরণ করুন', 'errors' => $errors]);
        exit;
    }
    
    // Check if email exists
    $stmt = Database::getInstance()->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->execute([$email]);
    if ($stmt->fetch()) {
        echo json_encode(['success' => false, 'message' => 'এই ইমেইল দিয়ে আগেই অ্যাকাউন্ট আছে']);
        exit;
    }
    
    // Check if phone exists
    $stmt = Database::getInstance()->prepare("SELECT id FROM users WHERE phone = ?");
    $stmt->execute([$phone]);
    if ($stmt->fetch()) {
        echo json_encode(['success' => false, 'message' => 'এই মোবাইল নম্বর দিয়ে আগেই অ্যাকাউন্ট আছে']);
        exit;
    }
    
    // Create user
    $passwordHash = password_hash($password, PASSWORD_DEFAULT);
    $stmt = Database::getInstance()->prepare(
        "INSERT INTO users (full_name, email, phone, password_hash, created_at) VALUES (?, ?, ?, ?, NOW())"
    );
    $stmt->execute([htmlspecialchars($fullName), $email, $phone, $passwordHash]);
    $userId = Database::getInstance()->lastInsertId();
    
    echo json_encode([
        'success' => true,
        'message' => 'রেজিস্ট্রেশন সফল হয়েছে! এখন লগইন করুন।',
        'data' => ['user_id' => $userId]
    ]);
    
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'ডাটাবেস ত্রুটি: ' . $e->getMessage()]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'ত্রুটি: ' . $e->getMessage()]);
}
