<?php
/**
 * صفحة التسجيل - Roz Skin
 * تصميم عصري مستوحى من تطبيقات الموبايل
 */

session_start();
require_once '../config/database.php';
require_once '../models/user.php';

if (isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit;
}

$database = new Database();
$conn = $database->getConnection();

$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    
    // Validate name (2 words, each at least 3 characters)
    $nameWords = preg_split('/\s+/', $name);
    $validNameWords = array_filter($nameWords, function($word) {
        return strlen($word) >= 3;
    });
    
    if (empty($name) || empty($phone) || empty($password)) {
        $message = 'جميع الحقول مطلوبة';
        $message_type = 'error';
    } elseif (count($validNameWords) < 2) {
        $message = 'الاسم يجب أن يتكون من كلمتين على الأقل، كل كلمة 3 حروف على الأقل';
        $message_type = 'error';
    } elseif (!preg_match('/^01[0-9]{9}$/', $phone)) {
        $message = 'رقم الهاتف يجب أن يكون 11 رقم ويبدأ بـ 01';
        $message_type = 'error';
    } elseif (strlen($password) < 6) {
        $message = 'كلمة المرور يجب أن تكون 6 أحرف على الأقل';
        $message_type = 'error';
    } elseif ($password !== $confirm_password) {
        $message = 'كلمة المرور غير متطابقة';
        $message_type = 'error';
    } else {
        try {
            $check = $conn->prepare("SELECT id FROM users WHERE phone = ?");
            $check->execute([$phone]);
            
            if ($check->rowCount() > 0) {
                $message = 'رقم الهاتف مسجل مسبقاً';
                $message_type = 'error';
            } else {
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $conn->prepare("INSERT INTO users (name, phone, password, created_at) VALUES (?, ?, ?, NOW())");
                
                if ($stmt->execute([$name, $phone, $hashed_password])) {
                    $user_id = $conn->lastInsertId();
                    $_SESSION['user_id'] = $user_id;
                    $_SESSION['user_name'] = $name;
                    $_SESSION['user_phone'] = $phone;
                    
                    header('Location: index.php');
                    exit;
                } else {
                    $message = 'حدث خطأ، حاول مرة أخرى';
                    $message_type = 'error';
                }
            }
        } catch (PDOException $e) {
            $message = 'حدث خطأ: ' . $e->getMessage();
            $message_type = 'error';
        }
    }
}

try {
    $settings_query = $conn->query("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('site_name', 'logo_text')");
    $settings = $settings_query->fetchAll(PDO::FETCH_KEY_PAIR);
    $site_name = $settings['site_name'] ?? 'Roz Skin';
    $logo_text = $settings['logo_text'] ?? 'Roz Skin';
} catch (Exception $e) {
    $site_name = 'Roz Skin';
    $logo_text = 'Roz Skin';
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إنشاء حساب - <?php echo htmlspecialchars($site_name); ?></title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Tajawal', sans-serif;
            min-height: 100vh;
            background: linear-gradient(135deg, #FFB6C1 0%, #FFA6B5 50%, #FF96A9 100%);
            position: relative;
            overflow-x: hidden;
        }
        
        body::before {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-image: 
                repeating-linear-gradient(45deg, transparent, transparent 35px, rgba(255,255,255,.05) 35px, rgba(255,255,255,.05) 70px),
                repeating-linear-gradient(-45deg, transparent, transparent 35px, rgba(255,255,255,.03) 35px, rgba(255,255,255,.03) 70px);
            pointer-events: none;
            z-index: 0;
        }
        
        .page-wrapper {
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            position: relative;
            z-index: 1;
        }
        
        /* Top Pink Section - 50% */
        .top-section {
            flex: 1;
            min-height: 50vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 60px 30px 100px;
            position: relative;
        }
        
        .logo-text {
            font-size: 52px;
            font-weight: 700;
            color: white;
            letter-spacing: -1px;
            text-shadow: 0 4px 20px rgba(0,0,0,0.15);
            margin-bottom: 15px;
            animation: fadeInDown 0.6s ease-out;
        }
        
        @keyframes fadeInDown {
            from {
                opacity: 0;
                transform: translateY(-30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .welcome-text {
            color: rgba(255,255,255,0.95);
            font-size: 17px;
            line-height: 1.7;
            text-align: center;
            animation: fadeInDown 0.6s ease-out 0.2s both;
        }
        
        /* Wave at 50% */
        .wave {
            position: absolute;
            bottom: -2px;
            left: 0;
            width: 100%;
            height: 120px;
        }
        
        /* Bottom White Section - 50% */
        .bottom-section {
            flex: 1;
            min-height: 50vh;
            background: white;
            padding: 50px 30px 40px;
            display: flex;
            align-items: flex-start;
            justify-content: center;
        }
        
        .form-container {
            width: 100%;
            max-width: 450px;
            animation: fadeInUp 0.6s ease-out 0.4s both;
        }
        
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .form-title {
            font-size: 32px;
            font-weight: 700;
            color: #333;
            margin-bottom: 5px;
            position: relative;
            display: inline-block;
        }
        
        .form-title::after {
            content: '';
            position: absolute;
            bottom: -4px;
            right: 0;
            width: 70%;
            height: 3px;
            background: #FF96A9;
            border-radius: 2px;
        }
        
        .form-subtitle {
            color: #999;
            font-size: 14px;
            margin-bottom: 30px;
        }
        
        .input-group {
            margin-bottom: 18px;
        }
        
        .input-group label {
            display: block;
            font-size: 13px;
            font-weight: 600;
            color: #666;
            margin-bottom: 8px;
        }
        
        .form-input-modern {
            width: 100%;
            padding: 18px 20px;
            border: none;
            border-bottom: 3px solid #f0f0f0;
            border-radius: 0;
            font-size: 18px;
            font-family: 'Tajawal', sans-serif;
            transition: all 0.3s;
            background: transparent;
            font-weight: 500;
        }
        
        .form-input-modern:focus {
            outline: none;
            border-bottom-color: #FF96A9;
            background: rgba(255, 150, 169, 0.03);
        }
        
        .form-input-modern::placeholder {
            color: #ccc;
            font-size: 16px;
            font-weight: 400;
        }
        
        .btn-confirm {
            width: 100%;
            padding: 14px;
            background: linear-gradient(135deg, #FFB6C1 0%, #FF96A9 100%);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            margin-top: 20px;
            box-shadow: 0 4px 15px rgba(255, 150, 169, 0.3);
        }
        
        .btn-confirm:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(255, 150, 169, 0.4);
        }
        
        .btn-submit {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #FFB6C1 0%, #FF96A9 100%);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 4px 15px rgba(255, 150, 169, 0.4);
            margin-top: 10px;
        }
        
        .btn-submit:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(255, 150, 169, 0.5);
        }
        
        .btn-submit:active {
            transform: translateY(0);
        }
        
        .form-footer {
            text-align: center;
            margin-top: 20px;
            font-size: 14px;
            color: #666;
        }
        
        .form-footer a {
            color: #FF96A9;
            text-decoration: none;
            font-weight: 600;
        }
        
        .message {
            padding: 12px 16px;
            border-radius: 10px;
            margin-bottom: 18px;
            font-size: 13px;
        }
        
        .message.error {
            background: #ffe8e8;
            color: #d63031;
            border: 1px solid #ffcccc;
        }
        
        .back-link {
            text-align: center;
            margin-top: 12px;
        }
        
        .back-link a {
            color: #999;
            text-decoration: none;
            font-size: 13px;
        }
        
        .back-link a:hover {
            color: #FF96A9;
        }
        
        .field-hint {
            display: block;
            color: #999;
            font-size: 12px;
            margin-top: 6px;
        }
        
        .progress-indicator {
            margin: 25px 0 20px;
        }
        
        .progress-bar {
            width: 100%;
            height: 6px;
            background: #f0f0f0;
            border-radius: 10px;
            overflow: hidden;
            margin-bottom: 8px;
        }
        
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #FFB6C1 0%, #FF96A9 100%);
            width: 20%;
            transition: width 0.4s ease;
            border-radius: 10px;
        }
        
        .progress-text {
            text-align: center;
            font-size: 13px;
            color: #666;
            font-weight: 500;
        }
        
        .btn-back {
            background: transparent;
            border: 1.5px solid #e0e0e0;
            color: #666;
            padding: 10px 20px;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
            margin-bottom: 20px;
            display: inline-block;
        }
        
        .btn-back:hover {
            border-color: #FF96A9;
            color: #FF96A9;
            background: rgba(255, 150, 169, 0.05);
        }
        
        /* AI Typing Indicator */
        .ai-indicator {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            padding: 15px;
            margin-bottom: 20px;
            background: linear-gradient(135deg, rgba(255, 182, 193, 0.1) 0%, rgba(255, 150, 169, 0.1) 100%);
            border-radius: 15px;
            border: 1px solid rgba(255, 150, 169, 0.2);
        }
        
        .ai-dot {
            width: 10px;
            height: 10px;
            background: linear-gradient(135deg, #FFB6C1 0%, #FF96A9 100%);
            border-radius: 50%;
            animation: aiPulse 1.4s infinite ease-in-out;
        }
        
        .ai-dot:nth-child(1) {
            animation-delay: 0s;
        }
        
        .ai-dot:nth-child(2) {
            animation-delay: 0.2s;
        }
        
        .ai-dot:nth-child(3) {
            animation-delay: 0.4s;
        }
        
        @keyframes aiPulse {
            0%, 60%, 100% {
                transform: scale(1);
                opacity: 0.7;
            }
            30% {
                transform: scale(1.3);
                opacity: 1;
            }
        }
        
        @keyframes slideInRight {
            from {
                opacity: 0;
                transform: translateX(-30px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }
        
        @keyframes slideInLeft {
            from {
                opacity: 0;
                transform: translateX(30px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }
        
        @keyframes slideInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        @media (max-width: 640px) {
            .logo-text {
                font-size: 42px;
            }
            
            .welcome-text {
                font-size: 15px;
            }
            
            .top-section {
                padding: 50px 20px 80px;
            }
            
            .bottom-section {
                padding: 40px 20px 30px;
            }
            
            .form-title {
                font-size: 28px;
            }
        }
    </style>
</head>
<body>
    <div class="page-wrapper">
        <!-- Top Pink Section with Logo -->
        <div class="top-section">
            <div class="logo-text"><?php echo htmlspecialchars($logo_text); ?></div>
            <div class="welcome-text">انضمي لعائلة الجمال والعناية<br>اكتشفي منتجاتنا الطبيعية 100%</div>
            
            <!-- Wave SVG -->
            <svg class="wave" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320" preserveAspectRatio="none">
                <path fill="#ffffff" fill-opacity="1" d="M0,96L48,112C96,128,192,160,288,160C384,160,480,128,576,122.7C672,117,768,139,864,138.7C960,139,1056,117,1152,101.3C1248,85,1344,75,1392,69.3L1440,64L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z"></path>
            </svg>
        </div>
        
        <!-- Bottom White Section with Form -->
        <div class="bottom-section">
            <div class="form-container">
                <h1 class="form-title">إنشاء حساب</h1>
                <p class="form-subtitle">املأ البيانات للانضمام إلينا</p>
                
                <?php if ($message): ?>
                    <div class="message <?php echo $message_type; ?>">
                        <?php echo htmlspecialchars($message); ?>
                    </div>
                <?php endif; ?>
                
                <form method="POST" id="registerForm">
                    <!-- AI Typing Indicator -->
                    <div class="ai-indicator" id="aiIndicator" style="display: none;">
                        <div class="ai-dot"></div>
                        <div class="ai-dot"></div>
                        <div class="ai-dot"></div>
                    </div>
                    
                    <!-- Back Button -->
                    <button type="button" class="btn-back" id="backBtn" style="display: none;" onclick="previousStep()">
                        ← رجوع
                    </button>
                    
                    <!-- Step 1: Name -->
                    <div class="input-group step-field" id="step1" style="display: block;">
                        <label for="name">ما اسمك؟</label>
                        <input type="text" id="name" name="name" class="form-input-modern" placeholder="أدخل اسمك الكامل" value="<?php echo htmlspecialchars($_POST['name'] ?? ''); ?>" autocomplete="off">
                        <small class="field-hint" id="nameHint">مثال: أحمد محمد أو Ahmed Mohamed</small>
                        <button type="button" class="btn-confirm" id="confirmName" style="display: none;" onclick="nextStep()">
                            تأكيد ←
                        </button>
                    </div>
                    
                    <!-- Step 2: Phone -->
                    <div class="input-group step-field" id="step2" style="display: none;">
                        <label for="phone">رقم هاتفك؟</label>
                        <input type="tel" id="phone" name="phone" class="form-input-modern" placeholder="01234567890" value="<?php echo htmlspecialchars($_POST['phone'] ?? ''); ?>" autocomplete="off">
                        <small class="field-hint">11 رقم تبدأ بـ 01</small>
                        <button type="button" class="btn-confirm" id="confirmPhone" style="display: none;" onclick="nextStep()">
                            تأكيد ←
                        </button>
                    </div>
                    
                    <!-- Step 3: Password -->
                    <div class="input-group step-field" id="step3" style="display: none;">
                        <label for="password">اختر كلمة مرور</label>
                        <input type="password" id="password" name="password" class="form-input-modern" placeholder="6 أحرف على الأقل" autocomplete="off">
                        <small class="field-hint">استخدم حروف وأرقام لأمان أفضل</small>
                        <button type="button" class="btn-confirm" id="confirmPassword" style="display: none;" onclick="nextStep()">
                            تأكيد ←
                        </button>
                    </div>
                    
                    <!-- Step 4: Confirm Password -->
                    <div class="input-group step-field" id="step4" style="display: none;">
                        <label for="confirm_password">أعد كتابة كلمة المرور</label>
                        <input type="password" id="confirm_password" name="confirm_password" class="form-input-modern" placeholder="للتأكيد" autocomplete="off">
                        <small class="field-hint">يجب أن تطابق كلمة المرور</small>
                        <button type="button" class="btn-confirm" id="confirmConfirmPassword" style="display: none;" onclick="showSubmitButton()">
                            تأكيد ←
                        </button>
                    </div>
                    
                    <!-- Progress Indicator -->
                    <div class="progress-indicator">
                        <div class="progress-bar">
                            <div class="progress-fill" id="progressFill"></div>
                        </div>
                        <div class="progress-text" id="progressText">الخطوة 1 من 5</div>
                    </div>
                    
                    <button type="submit" class="btn-submit" id="submitBtn" style="display: none;">إنشاء حساب</button>
                </form>
                
                <script>
                    let currentStep = 1;
                    const totalSteps = 4;
                    const formData = {};
                    
                    // Focus on first field
                    document.getElementById('name').focus();
                    
                    // Handle input for each field
                    document.getElementById('name').addEventListener('input', function(e) {
                        const value = e.target.value.trim();
                        const words = value.split(/\s+/).filter(w => w.length > 0);
                        const hint = document.getElementById('nameHint');
                        const confirmBtn = document.getElementById('confirmName');
                        
                        // Check if name has at least 2 words, each word at least 3 characters
                        const validWords = words.filter(w => w.length >= 3);
                        
                        if (validWords.length >= 2) {
                            hint.style.color = '#00cc66';
                            hint.textContent = '✓ رائع! الاسم صحيح';
                            formData.name = value;
                            confirmBtn.style.display = 'block';
                        } else {
                            confirmBtn.style.display = 'none';
                            if (words.length >= 2 && validWords.length < 2) {
                                hint.style.color = '#ff9800';
                                hint.textContent = '⚠ كل كلمة يجب أن تكون 3 حروف على الأقل';
                            } else if (words.length === 1) {
                                hint.style.color = '#999';
                                hint.textContent = 'أدخل الاسم الثاني...';
                            } else {
                                hint.style.color = '#999';
                                hint.textContent = 'مثال: أحمد محمد أو Ahmed Mohamed';
                            }
                        }
                    });
                    
                    document.getElementById('phone').addEventListener('input', function(e) {
                        const value = e.target.value.trim();
                        const confirmBtn = document.getElementById('confirmPhone');
                        
                        // Egyptian phone: 11 digits starting with 01
                        if (/^01[0-9]{9}$/.test(value)) {
                            formData.phone = value;
                            confirmBtn.style.display = 'block';
                        } else {
                            confirmBtn.style.display = 'none';
                        }
                    });
                    
                    document.getElementById('password').addEventListener('input', function(e) {
                        const value = e.target.value;
                        const confirmBtn = document.getElementById('confirmPassword');
                        
                        if (value.length >= 6) {
                            formData.password = value;
                            confirmBtn.style.display = 'block';
                        } else {
                            confirmBtn.style.display = 'none';
                        }
                    });
                    
                    document.getElementById('confirm_password').addEventListener('input', function(e) {
                        const value = e.target.value;
                        const confirmBtn = document.getElementById('confirmConfirmPassword');
                        
                        if (value === formData.password && value.length >= 6) {
                            formData.confirm_password = value;
                            confirmBtn.style.display = 'block';
                        } else {
                            confirmBtn.style.display = 'none';
                        }
                    });
                    
                    function nextStep() {
                        if (currentStep < totalSteps) {
                            // Hide current step
                            document.getElementById('step' + currentStep).style.display = 'none';
                            
                            // Show AI indicator
                            const aiIndicator = document.getElementById('aiIndicator');
                            aiIndicator.style.display = 'flex';
                            
                            // Wait a bit then show next step
                            setTimeout(() => {
                                aiIndicator.style.display = 'none';
                                
                                // Show next step
                                currentStep++;
                                const nextField = document.getElementById('step' + currentStep);
                                nextField.style.display = 'block';
                                nextField.style.animation = 'slideInRight 0.3s ease-out';
                                
                                // Focus on next input
                                const input = nextField.querySelector('input');
                                setTimeout(() => input.focus(), 100);
                                
                                // Show back button
                                document.getElementById('backBtn').style.display = 'inline-block';
                                
                                // Update progress
                                updateProgress();
                            }, 800);
                        }
                    }
                    
                    function previousStep() {
                        if (currentStep > 1) {
                            // Hide current step
                            const currentField = document.getElementById('step' + currentStep);
                            if (currentField) {
                                currentField.style.display = 'none';
                            }
                            
                            // Hide submit button if visible
                            document.getElementById('submitBtn').style.display = 'none';
                            
                            // Show previous step
                            currentStep--;
                            const prevField = document.getElementById('step' + currentStep);
                            prevField.style.display = 'block';
                            prevField.style.animation = 'slideInLeft 0.3s ease-out';
                            
                            // Focus on previous input
                            const input = prevField.querySelector('input');
                            setTimeout(() => input.focus(), 100);
                            
                            // Hide back button if on first step
                            if (currentStep === 1) {
                                document.getElementById('backBtn').style.display = 'none';
                            }
                            
                            // Update progress
                            updateProgress();
                        }
                    }
                    
                    function showSubmitButton() {
                        document.getElementById('step4').style.display = 'none';
                        
                        // Show AI indicator
                        const aiIndicator = document.getElementById('aiIndicator');
                        aiIndicator.style.display = 'flex';
                        
                        setTimeout(() => {
                            aiIndicator.style.display = 'none';
                            document.getElementById('submitBtn').style.display = 'block';
                            document.getElementById('submitBtn').style.animation = 'slideInUp 0.3s ease-out';
                            updateProgress();
                        }, 800);
                    }
                    
                    function updateProgress() {
                        const progress = (currentStep / totalSteps) * 100;
                        document.getElementById('progressFill').style.width = progress + '%';
                        document.getElementById('progressText').textContent = 'الخطوة ' + currentStep + ' من ' + totalSteps;
                    }
                    
                    // Allow Enter key to move to next field
                    document.querySelectorAll('.form-input').forEach(input => {
                        input.addEventListener('keypress', function(e) {
                            if (e.key === 'Enter') {
                                e.preventDefault();
                            }
                        });
                    });
                </script>
                
                <div class="form-footer">
                    لديك حساب بالفعل؟ <a href="login.php">تسجيل الدخول</a>
                </div>
                
                <div class="back-link">
                    <a href="index.php">← العودة للمتجر</a>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
