<?php
// auth.php - Working Login System (Google Login ready when configured)
require_once 'includes/config.php';
require_once 'includes/site-data.php'; // ← ADD THIS

if(isset($_SESSION['user_id'])) {
    header('Location: dashboard.php');
    exit;
}

// ==================== GOOGLE CONFIGURATION ====================
// Set to false until you have working Google credentials
$google_enabled = false; // Change to true when Google OAuth is properly set up
$google_client_id = 'YOUR_CLIENT_ID.apps.googleusercontent.com';
$google_client_secret = 'YOUR_CLIENT_SECRET';
$google_redirect_url = 'https://onesbd.com/LMS/auth.php?action=google_callback';
// =============================================================

$error = '';
$success = '';
$action = $_POST['action'] ?? 'login';
$step = $_POST['step'] ?? $_GET['step'] ?? 'form';

// ==================== HANDLE LOGIN ====================
if($_SERVER['REQUEST_METHOD'] == 'POST' && $action == 'login') {
    $email = filter_var($_POST['email'] ?? '', FILTER_SANITIZE_EMAIL);
    $password = $_POST['password'] ?? '';
    
    if(empty($email) || empty($password)) {
        $error = 'ইমেইল এবং পাসওয়ার্ড প্রয়োজন';
    } else {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch();
        
        if($user && password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_role'] = $user['role'];
            $_SESSION['user_name'] = $user['full_name'];
            header('Location: dashboard.php');
            exit;
        } else {
            $error = 'ইমেইল অথবা পাসওয়ার্ড ভুল';
        }
    }
}

// ==================== HANDLE REGISTRATION ====================
if($_SERVER['REQUEST_METHOD'] == 'POST' && $action == 'register') {
    $name = trim($_POST['full_name'] ?? '');
    $email = filter_var($_POST['email'] ?? '', FILTER_SANITIZE_EMAIL);
    $phone = trim($_POST['phone'] ?? '');
    $pass = $_POST['password'] ?? '';
    $cpass = $_POST['confirm_password'] ?? '';
    
    if(empty($name) || empty($email) || empty($phone) || empty($pass)) {
        $error = 'সকল তথ্য পূরণ করুন';
    } elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'সঠিক ইমেইল লিখুন';
    } elseif($pass !== $cpass) {
        $error = 'পাসওয়ার্ড মিলছে না';
    } elseif(strlen($pass) < 6) {
        $error = 'পাসওয়ার্ড কমপক্ষে ৬ অক্ষর';
    } else {
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->execute([$email]);
        if($stmt->fetch()) {
            $error = 'ইমেইল ইতিমধ্যে নিবন্ধিত';
        } else {
            $hash = password_hash($pass, PASSWORD_DEFAULT);
            
            $stmt = $pdo->prepare("INSERT INTO users (full_name, email, phone, password, phone_verified, role) VALUES (?,?,?,?,1,'student')");
            $stmt->execute([$name, $email, $phone, $hash]);
            
            // Role-based redirect
    if($user['role'] == 'admin' || $user['role'] == 'instructor') {
        header('Location: admin/dashboard.php');
    } else {
       if(($user['role'] ?? 'student') == 'admin' || ($user['role'] ?? 'student') == 'instructor') {
    header('Location: admin/dashboard.php');
} else {
    header('Location: dashboard.php');
}
$redirect_role = $user['role'] ?? 'student';
if($redirect_role == 'admin' || $redirect_role == 'instructor') {
    header('Location: admin/dashboard.php');
} else {
    header('Location: dashboard.php');
}
    }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title><?= htmlspecialchars($S['site_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: #6C5CE7; --gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { min-height: 100vh; background: var(--gradient); display: flex; align-items: center; justify-content: center; font-family: 'Segoe UI', 'Hind Siliguri', Arial, sans-serif; padding: 20px; }
        .auth-card { background: white; border-radius: 24px; box-shadow: 0 25px 60px rgba(0,0,0,0.3); width: 100%; max-width: 440px; overflow: hidden; animation: slideUp 0.5s ease; }
        @keyframes slideUp { from { opacity: 0; transform: translateY(30px); } to { opacity: 1; transform: translateY(0); } }
        .card-header { background: var(--gradient); color: white; padding: 30px 25px; text-align: center; }
        .card-header .icon-circle { width: 60px; height: 60px; background: rgba(255,255,255,0.2); border-radius: 50%; display: inline-flex; align-items: center; justify-content: center; font-size: 1.5rem; margin-bottom: 12px; animation: pulse 2s infinite; }
        @keyframes pulse { 0% { box-shadow: 0 0 0 0 rgba(255,255,255,0.4); } 70% { box-shadow: 0 0 0 20px rgba(255,255,255,0); } 100% { box-shadow: 0 0 0 0 rgba(255,255,255,0); } }
        .card-body { padding: 30px 25px; }
        .tabs { display: flex; gap: 5px; margin-bottom: 22px; }
        .tab-btn { flex: 1; padding: 10px; text-align: center; background: #f0f0f0; border-radius: 10px; cursor: pointer; font-weight: 600; font-size: 0.85rem; border: none; transition: 0.3s; }
        .tab-btn.active { background: var(--primary); color: white; }
        .form-panel { display: none; }
        .form-panel.active { display: block; }
        .form-group { margin-bottom: 18px; }
        .form-group label { font-weight: 600; font-size: 0.9rem; margin-bottom: 5px; display: block; color: #333; }
        .form-group input { width: 100%; padding: 12px 15px; border: 2px solid #e0e0e0; border-radius: 10px; font-size: 0.95rem; transition: 0.3s; }
        .form-group input:focus { border-color: var(--primary); outline: none; box-shadow: 0 0 0 3px rgba(108,92,231,0.1); }
        .btn-submit { width: 100%; padding: 13px; background: var(--gradient); color: white; border: none; border-radius: 25px; font-size: 1rem; font-weight: 600; cursor: pointer; transition: 0.3s; margin-top: 5px; }
        .btn-submit:hover { transform: translateY(-2px); box-shadow: 0 10px 20px rgba(108,92,231,0.4); }
        .btn-google { width: 100%; padding: 12px; background: white; color: #333; border: 2px solid #ddd; border-radius: 25px; font-size: 0.95rem; font-weight: 500; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 10px; transition: 0.3s; text-decoration: none; margin-top: 10px; }
        .btn-google:hover { background: #f5f5f5; }
        .btn-google img { width: 20px; height: 20px; }
        .divider { display: flex; align-items: center; margin: 20px 0; color: #999; font-size: 0.85rem; }
        .divider::before, .divider::after { content: ''; flex: 1; border-bottom: 1px solid #e0e0e0; }
        .divider span { padding: 0 12px; }
        .alert { padding: 12px 15px; border-radius: 10px; margin-bottom: 18px; font-size: 0.9rem; }
        .alert-danger { background: #ffeaea; color: #c33; border: 1px solid #fcc; }
        .alert-success { background: #eaffea; color: #3a3; border: 1px solid #cfc; }
    </style>
</head>
<body>

<div class="auth-card">
    <div class="card-header">
        <div class="icon-circle"><i class="fas fa-graduation-cap"></i></div>
       <?= htmlspecialchars($S['logo_text'] ?? 'বাংলা LMS') ?>
        <p>আপনার অ্যাকাউন্টে লগইন করুন</p>
    </div>
    
    <div class="card-body">
        <?php if($error): ?>
            <div class="alert alert-danger"><i class="fas fa-exclamation-circle me-2"></i><?= $error ?></div>
        <?php endif; ?>
        <?php if($success): ?>
            <div class="alert alert-success"><i class="fas fa-check-circle me-2"></i><?= $success ?></div>
        <?php endif; ?>
        
        <!-- Tab Navigation -->
        <div class="tabs">
            <button class="tab-btn active" onclick="switchTab('login')">লগইন</button>
            <button class="tab-btn" onclick="switchTab('register')">রেজিস্ট্রেশন</button>
        </div>
        
        <!-- Login Form -->
        <div class="form-panel active" id="loginPanel">
            <form method="POST" action="">
                <input type="hidden" name="action" value="login">
                <div class="form-group">
                    <label><i class="fas fa-envelope me-1"></i> ইমেইল</label>
                    <input type="email" name="email" placeholder="admin@banglalms.com" required>
                </div>
                <div class="form-group">
                    <label><i class="fas fa-lock me-1"></i> পাসওয়ার্ড</label>
                    <input type="password" name="password" placeholder="আপনার পাসওয়ার্ড" required>
                </div>
                <button type="submit" class="btn-submit">
                    <i class="fas fa-sign-in-alt me-2"></i> লগইন করুন
                </button>
            </form>
        </div>
        
        <!-- Register Form -->
        <div class="form-panel" id="registerPanel">
            <form method="POST" action="">
                <input type="hidden" name="action" value="register">
                <div class="form-group"><label>পূর্ণ নাম</label><input type="text" name="full_name" placeholder="আপনার নাম" required></div>
                <div class="form-group"><label>ইমেইল</label><input type="email" name="email" placeholder="example@email.com" required></div>
                <div class="form-group"><label>ফোন নম্বর</label><input type="text" name="phone" placeholder="01XXXXXXXXX" required></div>
                <div class="form-group"><label>পাসওয়ার্ড</label><input type="password" name="password" placeholder="কমপক্ষে ৬ অক্ষর" required></div>
                <div class="form-group"><label>পাসওয়ার্ড নিশ্চিত করুন</label><input type="password" name="confirm_password" placeholder="পাসওয়ার্ড আবার লিখুন" required></div>
                <button type="submit" class="btn-submit"><i class="fas fa-user-plus me-2"></i> রেজিস্ট্রেশন করুন</button>
            </form>
        </div>
        
        <!-- Divider & Google Login (disabled until configured) -->
        <div class="divider"><span>অথবা</span></div>
        
        <?php if($google_enabled): ?>
            <a href="https://accounts.google.com/o/oauth2/v2/auth?<?= http_build_query(['client_id'=>$google_client_id,'redirect_uri'=>$google_redirect_url,'response_type'=>'code','scope'=>'email profile','access_type'=>'online']) ?>" class="btn-google">
                <img src="https://www.google.com/favicon.ico" alt="G"> Google দিয়ে লগইন করুন
            </a>
        <?php else: ?>
            <button class="btn-google" onclick="alert('Google Login শীঘ্রই আসছে! বর্তমানে ইমেইল ও পাসওয়ার্ড দিয়ে লগইন করুন।')" style="opacity:0.7;">
                <img src="https://www.google.com/favicon.ico" alt="G"> Google দিয়ে লগইন করুন (শীঘ্রই আসছে)
            </button>
        <?php endif; ?>
        
        <p class="text-center mt-3" style="font-size:0.85rem;">
            অ্যাকাউন্ট নেই? <a href="#" onclick="switchTab('register')" style="color:var(--primary);font-weight:600;">রেজিস্ট্রেশন করুন</a>
        </p>
    </div>
</div>

<script>
function switchTab(tab) {
    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    document.querySelectorAll('.form-panel').forEach(p => p.classList.remove('active'));
    if(tab === 'login') {
        document.querySelectorAll('.tab-btn')[0].classList.add('active');
        document.getElementById('loginPanel').classList.add('active');
    } else {
        document.querySelectorAll('.tab-btn')[1].classList.add('active');
        document.getElementById('registerPanel').classList.add('active');
    }
}
</script>
</body>
</html>