<?php
require_once 'includes/config.php';

if(isLoggedIn()) {
    header('Location: dashboard.php');
    exit;
}

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

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $full_name = trim($_POST['full_name']);
    $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
    $phone = trim($_POST['phone']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    $agree = isset($_POST['agree']);
    
    // Validation
    if(empty($full_name) || empty($email) || empty($password)) {
        $error = 'সকল প্রয়োজনীয় তথ্য পূরণ করুন';
    } elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'সঠিক ইমেইল অ্যাড্রেস লিখুন';
    } elseif(strlen($password) < 6) {
        $error = 'পাসওয়ার্ড কমপক্ষে ৬ অক্ষরের হতে হবে';
    } elseif($password !== $confirm_password) {
        $error = 'পাসওয়ার্ড মিলছে না';
    } elseif(!$agree) {
        $error = 'আপনাকে শর্তাবলী মেনে নিতে হবে';
    } else {
        // Check if email exists
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->execute([$email]);
        
        if($stmt->rowCount() > 0) {
            $error = 'এই ইমেইল অ্যাড্রেসটি ইতিমধ্যে নিবন্ধিত';
        } else {
            // Hash password
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            
            // Handle avatar upload
            $avatar = 'default-avatar.png';
            if(isset($_FILES['avatar']) && $_FILES['avatar']['error'] == 0) {
                $allowed = ['jpg', 'jpeg', 'png', 'gif'];
                $filename = $_FILES['avatar']['name'];
                $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
                
                if(in_array($ext, $allowed)) {
                    $avatar = time() . '_' . uniqid() . '.' . $ext;
                    move_uploaded_file($_FILES['avatar']['tmp_name'], 'uploads/avatars/' . $avatar);
                }
            }
            
            // Insert user
            $stmt = $pdo->prepare("
                INSERT INTO users (full_name, email, password, phone, avatar, role) 
                VALUES (?, ?, ?, ?, ?, 'student')
            ");
            
            try {
                $stmt->execute([$full_name, $email, $hashed_password, $phone, $avatar]);
                
                $_SESSION['success'] = 'রেজিস্ট্রেশন সফল হয়েছে! এখন লগইন করুন।';
                header('Location: login.php');
                exit;
            } catch(PDOException $e) {
                $error = 'রেজিস্ট্রেশন ব্যর্থ হয়েছে। আবার চেষ্টা করুন।';
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>রেজিস্ট্রেশন - বাংলা LMS</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #6C5CE7;
            --gradient-1: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        body {
            min-height: 100vh;
            background: var(--gradient-1);
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: 'Hind Siliguri', 'SolaimanLipi', sans-serif;
            padding: 20px;
        }
        
        .register-container {
            background: white;
            border-radius: 30px;
            box-shadow: 0 30px 60px rgba(0,0,0,0.2);
            overflow: hidden;
            width: 100%;
            max-width: 600px;
            animation: slideUp 0.5s ease;
        }
        
        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateY(50px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .register-header {
            background: var(--gradient-1);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .register-header h2 {
            font-size: 2rem;
            font-weight: 700;
        }
        
        .register-body {
            padding: 30px;
        }
        
        .form-control {
            border-radius: 12px;
            padding: 10px 15px;
            border: 2px solid #e0e0e0;
            transition: all 0.3s ease;
        }
        
        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.2rem rgba(108, 92, 231, 0.25);
        }
        
        .btn-register {
            background: var(--gradient-1);
            border: none;
            border-radius: 50px;
            padding: 12px;
            font-size: 1.1rem;
            font-weight: 600;
            color: white;
            width: 100%;
            transition: all 0.3s ease;
        }
        
        .btn-register:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 25px rgba(108, 92, 231, 0.4);
        }
        
        .avatar-upload {
            position: relative;
            width: 100px;
            height: 100px;
            margin: 0 auto 20px;
        }
        
        .avatar-upload img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            object-fit: cover;
            border: 3px solid var(--primary-color);
        }
        
        .avatar-upload input {
            position: absolute;
            bottom: 0;
            right: 0;
            width: 30px;
            height: 30px;
            opacity: 0;
            cursor: pointer;
        }
        
        .avatar-upload .upload-icon {
            position: absolute;
            bottom: 0;
            right: 0;
            width: 30px;
            height: 30px;
            background: var(--primary-color);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            cursor: pointer;
        }
    </style>
</head>
<body>

<div class="register-container">
    <div class="register-header">
        <i class="fas fa-user-plus fa-3x mb-3"></i>
        <h2>রেজিস্ট্রেশন</h2>
        <p>বাংলা LMS এ স্বাগতম</p>
    </div>
    
    <div class="register-body">
        <?php if($error): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-triangle"></i> <?php echo $error; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
            
            <div class="avatar-upload">
                <img src="uploads/avatars/default-avatar.png" id="avatarPreview" alt="Avatar">
                <input type="file" name="avatar" accept="image/*" onchange="previewImage(this)">
                <div class="upload-icon">
                    <i class="fas fa-camera"></i>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">পূর্ণ নাম *</label>
                    <input type="text" name="full_name" class="form-control" 
                           placeholder="আপনার নাম লিখুন" required>
                </div>
                
                <div class="col-md-6 mb-3">
                    <label class="form-label">ইমেইল *</label>
                    <input type="email" name="email" class="form-control" 
                           placeholder="example@email.com" required>
                </div>
            </div>
            
            <div class="mb-3">
                <label class="form-label">ফোন নম্বর (ঐচ্ছিক)</label>
                <input type="text" name="phone" class="form-control" 
                       placeholder="০১XXXXXXXXX">
            </div>
            
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">পাসওয়ার্ড *</label>
                    <input type="password" name="password" class="form-control" 
                           placeholder="কমপক্ষে ৬ অক্ষর" required id="password">
                    <div class="password-strength mt-2">
                        <div class="progress" style="height: 5px;">
                            <div class="progress-bar" id="passwordStrength" style="width: 0%"></div>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-6 mb-3">
                    <label class="form-label">পাসওয়ার্ড নিশ্চিত করুন *</label>
                    <input type="password" name="confirm_password" class="form-control" 
                           placeholder="পাসওয়ার্ড আবার লিখুন" required>
                </div>
            </div>
            
            <div class="mb-3 form-check">
                <input type="checkbox" class="form-check-input" name="agree" id="agree">
                <label class="form-check-label" for="agree">
                    আমি <a href="terms.php" target="_blank">শর্তাবলী</a> এবং 
                    <a href="privacy.php" target="_blank">গোপনীয়তা নীতি</a> মেনে নিচ্ছি
                </label>
            </div>
            
            <button type="submit" class="btn btn-register mb-3">
                <i class="fas fa-user-plus me-2"></i> রেজিস্ট্রেশন করুন
            </button>
        </form>
        
        <p class="text-center mb-0">
            ইতিমধ্যে অ্যাকাউন্ট আছে? <a href="login.php" class="text-decoration-none fw-bold">লগইন করুন</a>
        </p>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
function previewImage(input) {
    if(input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('avatarPreview').src = e.target.result;
        }
        reader.readAsDataURL(input.files[0]);
    }
}

// Password strength checker
document.getElementById('password').addEventListener('input', function(e) {
    const password = e.target.value;
    let strength = 0;
    
    if(password.length >= 6) strength += 25;
    if(password.match(/[a-z]+/)) strength += 25;
    if(password.match(/[A-Z]+/)) strength += 25;
    if(password.match(/[0-9]+/)) strength += 25;
    
    const strengthBar = document.getElementById('passwordStrength');
    strengthBar.style.width = strength + '%';
    
    if(strength <= 25) strengthBar.style.backgroundColor = '#dc3545';
    else if(strength <= 50) strengthBar.style.backgroundColor = '#ffc107';
    else if(strength <= 75) strengthBar.style.backgroundColor = '#0dcaf0';
    else strengthBar.style.backgroundColor = '#198754';
});
</script>

</body>
</html>