<?php
session_start();
require_once 'config/database.php';

// Check if user is already logged in
if (isset($_SESSION['user_id']) && isset($_SESSION['user_role']) && $_SESSION['user_role'] == 'student') {
    header('Location: student_dashboard.php');
    exit();
}

$error_message = '';

// Check if customer_number column exists in students table
$tableHasCustomerNumber = false;
try {
    $checkColumnStmt = $pdo->query("SHOW COLUMNS FROM students LIKE 'customer_number'");
    $tableHasCustomerNumber = $checkColumnStmt->rowCount() > 0;
} catch (Exception $e) {
    // If there's an error checking the column, assume it doesn't exist
    $tableHasCustomerNumber = false;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $identifier = isset($_POST['identifier']) ? trim($_POST['identifier']) : '';
    $password = $_POST['password'];
    $login_type = $_POST['login_type'] ?? 'customer'; // 'customer' or 'user_id'

    if (empty($identifier) || empty($password)) {
        $error_message = 'লগইন তথ্য সম্পূর্ণ দিন';
    } else {
        try {
            $student = null;
            
            if ($login_type === 'customer' && $tableHasCustomerNumber) {
                // Login using customer number
                $stmt = $pdo->prepare("
                    SELECT s.*, u.id as user_id, u.password as user_password 
                    FROM students s 
                    LEFT JOIN users u ON s.user_id = u.id 
                    WHERE s.customer_number = ?
                ");
                $stmt->execute([$identifier]);
                $student = $stmt->fetch();
                
                if ($student && $password === '123456') {
                    // Successful login with customer number and default password
                    $_SESSION['user_id'] = $student['user_id'];
                    $_SESSION['user_role'] = 'student';
                    $_SESSION['student_id'] = $student['id'];
                    $_SESSION['student_customer_number'] = $student['customer_number'];
                    $_SESSION['student_name'] = $student['first_name'] . ' ' . $student['last_name'];
                    
                    header('Location: student_dashboard.php');
                    exit();
                }
            } else if ($login_type === 'user_id') {
                // Login using user ID (student ID)
                $stmt = $pdo->prepare("
                    SELECT s.*, u.id as user_id, u.password as user_password, u.username
                    FROM students s 
                    JOIN users u ON s.user_id = u.id 
                    WHERE s.student_id = ? AND u.role = 'student'
                ");
                $stmt->execute([$identifier]);
                $student = $stmt->fetch();
                
                if ($student && $password === '123456') {
                    // Successful login with student ID and default password
                    $_SESSION['user_id'] = $student['user_id'];
                    $_SESSION['user_role'] = 'student';
                    $_SESSION['student_id'] = $student['id'];
                    $_SESSION['student_customer_number'] = $student['customer_number'] ?? null;
                    $_SESSION['student_name'] = $student['first_name'] . ' ' . $student['last_name'];
                    
                    header('Location: student_dashboard.php');
                    exit();
                }
            } else if ($login_type === 'customer' && !$tableHasCustomerNumber) {
                // If trying to login with customer number but column doesn't exist, show error
                $error_message = 'গ্রাহক নম্বর লগইন বর্তমানে সক্রিয় নেই। ছাত্র আইডি দিয়ে চেষ্টা করুন।';
            }
            
            // If we get here, login failed
            if (empty($error_message)) {
                $error_message = 'ভুল লগইন তথ্য! অনুগ্রহ করে সঠিক তথ্য দিন।';
            }
            
        } catch (Exception $e) {
            $error_message = 'লগইনে সমস্যা হয়েছে: ' . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>শিক্ষার্থী লগইন - বিদ্যা নিকেতন</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            background: linear-gradient(135deg, #006747 0%, #004d35 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            padding: 20px;
        }
        
        .login-container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            overflow: hidden;
            max-width: 500px;
            width: 100%;
        }
        
        .login-header {
            background: linear-gradient(135deg, #006747 0%, #004d35 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .login-header h2 {
            margin: 0;
            font-weight: 700;
        }
        
        .login-body {
            padding: 30px;
        }
        
        .btn-login {
            background: linear-gradient(135deg, #006747 0%, #004d35 100%);
            border: none;
            padding: 12px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .btn-login:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 103, 71, 0.4);
        }
        
        .form-check-input:checked {
            background-color: #006747;
            border-color: #006747;
        }
        
        .identifier-toggle {
            cursor: pointer;
            color: #006747;
            font-weight: 500;
        }
        
        .identifier-toggle:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8 col-lg-6">
                <div class="login-container">
                    <div class="login-header">
                        <h2><i class="fas fa-user-graduate"></i> শিক্ষার্থী লগইন</h2>
                        <p class="mb-0">গ্রাহক নম্বর অথবা ছাত্র আইডি দিয়ে লগইন করুন</p>
                    </div>
                    
                    <div class="login-body">
                        <?php if ($error_message): ?>
                            <div class="alert alert-danger">
                                <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
                            </div>
                        <?php endif; ?>
                        
                        <form method="POST" action="">
                            <!-- Login Type Toggle -->
                            <div class="mb-3">
                                <label class="form-label">লগইন পদ্ধতি নির্বাচন করুন:</label>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="login_type" id="login_customer" value="customer" checked>
                                    <label class="form-check-label" for="login_customer">
                                        <i class="fas fa-user-tag"></i> গ্রাহক নম্বর দিয়ে
                                    </label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="login_type" id="login_userid" value="user_id">
                                    <label class="form-check-label" for="login_userid">
                                        <i class="fas fa-id-card"></i> ছাত্র আইডি দিয়ে
                                    </label>
                                </div>
                            </div>
                            
                            <!-- Identifier Field (changes based on selection) -->
                            <div class="mb-3">
                                <label for="identifier" class="form-label" id="identifier_label">গ্রাহক নম্বর</label>
                                <input type="text" class="form-control" id="identifier" name="identifier" 
                                       value="<?php echo isset($_POST['identifier']) ? htmlspecialchars($_POST['identifier']) : ''; ?>" 
                                       placeholder="গ্রাহক নম্বর লিখুন" required>
                                <div class="form-text" id="identifier_help">গ্রাহক নম্বর হিসেবে লগইন করুন</div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="password" class="form-label">পাসওয়ার্ড</label>
                                <input type="password" class="form-control" id="password" name="password" required>
                                <div class="form-text">আপনার পাসওয়ার্ড দিন</div>
                            </div>
                            
                            <div class="d-grid">
                                <button type="submit" class="btn btn-login">
                                    <i class="fas fa-sign-in-alt"></i> লগইন
                                </button>
                            </div>
                        </form>
                        
                        <div class="mt-3 text-center">
                            <p class="text-muted">প্রাথমিক পাসওয়ার্ড: <strong>123456</strong></p>
                            <p class="text-muted">পরবর্তীতে পাসওয়ার্ড পরিবর্তন করা যেতে পারে</p>
                        </div>
                        
                        <div class="navigation-links text-center mt-3">
                            <a href="login.php" class="btn btn-outline-secondary btn-sm">
                                <i class="fas fa-arrow-left"></i> মূল লগইন পেজে ফিরে যান
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const loginCustomer = document.getElementById('login_customer');
            const loginUserId = document.getElementById('login_userid');
            const identifierLabel = document.getElementById('identifier_label');
            const identifierInput = document.getElementById('identifier');
            const identifierHelp = document.getElementById('identifier_help');
            
            function updateForm() {
                if (loginCustomer.checked) {
                    identifierLabel.innerHTML = 'গ্রাহক নম্বর';
                    identifierInput.placeholder = 'গ্রাহক নম্বর লিখুন';
                    identifierInput.name = 'identifier';
                    identifierHelp.innerHTML = 'আপনার গ্রাহক নম্বর দিয়ে লগইন করুন';
                } else {
                    identifierLabel.innerHTML = 'ছাত্র আইডি';
                    identifierInput.placeholder = 'ছাত্র আইডি লিখুন';
                    identifierInput.name = 'identifier';
                    identifierHelp.innerHTML = 'আপনার ছাত্র আইডি দিয়ে লগইন করুন';
                }
            }
            
            loginCustomer.addEventListener('change', updateForm);
            loginUserId.addEventListener('change', updateForm);
            
            // Initialize form
            updateForm();
        });
    </script>
</body>
</html>