<?php
require_once 'config.php';

$error = '';
$success = '';

if($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $full_name = trim($_POST['full_name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $password = $_POST['password'] ?? '';
    
    if(empty($username) || empty($email) || empty($password) || empty($full_name)) {
        $error = "Заполните все обязательные поля";
    } elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Некорректный email";
    } elseif(strlen($password) < 4) {
        $error = "Пароль должен быть не менее 4 символов";
    } else {
        $phone_clean = preg_replace('/[^0-9]/', '', $phone);
        if(strlen($phone_clean) === 11 && $phone_clean[0] === '7') {
            $phone_clean = '+' . $phone_clean;
        }
        
        $hash = password_hash($password, PASSWORD_DEFAULT);
        try {
            $stmt = $pdo->prepare("INSERT INTO users (username, email, full_name, phone, password_hash) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$username, $email, $full_name, $phone_clean, $hash]);
            $success = "✅ Регистрация успешна! <a href='login.php'>Войти</a>";
        } catch(PDOException $e) {
            $error = "Пользователь с таким именем или email уже существует";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <title>Регистрация - Благотворительный фонд</title>
    <meta name="description" content="Создайте аккаунт для помощи нуждающимся">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', Arial, sans-serif; background: linear-gradient(135deg, #0f766e 0%, #14b8a6 100%); min-height: 100vh; display: flex; justify-content: center; align-items: center; }
        .form-box { background: #fff; padding: 40px; border-radius: 16px; width: 450px; box-shadow: 0 20px 40px rgba(0,0,0,0.2); }
        h1 { margin-bottom: 25px; text-align: center; color: #0f172a; }
        input { width: 100%; padding: 12px; margin: 8px 0 16px; border: 1px solid #ddd; border-radius: 8px; font-size: 16px; }
        input:focus { outline: none; border-color: #0f766e; }
        button { width: 100%; padding: 12px; background: #0f766e; color: #fff; border: none; border-radius: 8px; cursor: pointer; font-size: 16px; font-weight: bold; }
        button:hover { background: #0d5c56; }
        .error { color: #e74c3c; margin: 10px 0; padding: 10px; background: #fdecea; border-radius: 8px; }
        .success { color: #27ae60; margin: 10px 0; padding: 10px; background: #e8f5e9; border-radius: 8px; }
        .link { text-align: center; margin-top: 20px; }
        a { color: #0f766e; text-decoration: none; }
        .phone-hint { font-size: 12px; color: #7f8c8d; margin-top: -12px; margin-bottom: 12px; }
    </style>
</head>
<body>
<div class="form-box">
    <h1>🤝 Регистрация</h1>
    <?php if($error): ?><div class="error"><?= h($error) ?></div><?php endif; ?>
    <?php if($success): ?><div class="success"><?= $success ?></div><?php endif; ?>
    <form method="POST">
        <input type="text" name="username" placeholder="👤 Имя пользователя" required>
        <input type="text" name="full_name" placeholder="📝 Ваше полное имя" required>
        <input type="email" name="email" placeholder="📧 Email" required>
        <input type="tel" name="phone" id="phone" placeholder="📞 Телефон" value="+7 (">
        <div class="phone-hint">📱 Формат: +7 (777) 777 77 77</div>
        <input type="password" name="password" placeholder="🔒 Пароль (мин. 4)" required>
        <button type="submit">Зарегистрироваться</button>
    </form>
    <div class="link">Уже есть аккаунт? <a href="login.php">Войти</a></div>
</div>

<script>
    const phoneInput = document.getElementById('phone');
    phoneInput.addEventListener('input', function(e) {
        let value = e.target.value.replace(/\D/g, '');
        let formatted = '';
        if(value.length === 0) formatted = '+7 (';
        else if(value.length <= 1) formatted = '+7 (' + value;
        else if(value.length <= 4) formatted = '+7 (' + value.slice(1, 4);
        else if(value.length <= 7) formatted = '+7 (' + value.slice(1, 4) + ') ' + value.slice(4, 7);
        else if(value.length <= 9) formatted = '+7 (' + value.slice(1, 4) + ') ' + value.slice(4, 7) + ' ' + value.slice(7, 9);
        else formatted = '+7 (' + value.slice(1, 4) + ') ' + value.slice(4, 7) + ' ' + value.slice(7, 9) + ' ' + value.slice(9, 11);
        e.target.value = formatted;
    });
    phoneInput.addEventListener('focus', function(e) {
        if(e.target.value === '+7 (' || e.target.value === '') {
            e.target.value = '+7 (';
            e.target.setSelectionRange(4, 4);
        }
    });
</script>
</body>
</html>