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

// Function to create temporary password notifications table
function createTempPasswordNotificationsTable($pdo) {
    $pdo->exec(
        "CREATE TABLE IF NOT EXISTS temp_password_notifications (
            id INT AUTO_INCREMENT PRIMARY KEY,
            username VARCHAR(50) NOT NULL,
            temp_password VARCHAR(255) NOT NULL,
            expires_at DATETIME NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            UNIQUE KEY unique_username (username)
        )"
    );
}

// Create the table if it doesn't exist
createTempPasswordNotificationsTable($pdo);

// Check if user is already logged in with complete session data
if (isset($_SESSION['student_logged_in']) && $_SESSION['student_logged_in'] === true) {
    // Check if we have the essential session variables
    if (isset($_SESSION['student_application_no']) || isset($_SESSION['student_id']) || isset($_SESSION['student_customer_number'])) {
        // Only redirect if we're not already processing a login request
        if (!isset($_POST['customer_number']) && empty($_POST)) {
            header('Location: student_dashboard.php');
            exit();
        }
    }
    // If logged in but missing critical session data, we'll allow login flow to refresh
}

// Check if user is already logged in with complete session data (for customer number login)
if (isset($_SESSION['user_id']) && isset($_SESSION['user_role']) && $_SESSION['user_role'] == 'student') {
    header('Location: student_dashboard.php');
    exit();
}


$error_message = '';

// Check for error message from redirect
if (isset($_SESSION['error_message'])) {
    $error_message = $_SESSION['error_message'];
    unset($_SESSION['error_message']);
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $customer_number = isset($_POST['customer_number']) ? trim($_POST['customer_number']) : '';
    $password = $_POST['password'];

    // Handle login based on customer number (primary method)
    if (!empty($customer_number) && !empty($password)) {
        try {
            // Login using customer number and default password '123456'
            if ($password === '123456') {
                $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([$customer_number]);
                $student = $stmt->fetch();
                
                if ($student) {
                    // Set session variables for student login using customer number
                    $_SESSION['user_id'] = $student['user_id'] ?? null;
                    $_SESSION['user_role'] = 'student';
                    $_SESSION['username'] = $student['customer_number']; // Use customer number as username
                    $_SESSION['user_name'] = $student['first_name'] . ' ' . $student['last_name'];
                    $_SESSION['student_id'] = $student['id'];
                    $_SESSION['student_customer_number'] = $student['customer_number'];
                    $_SESSION['student_application_no'] = $student['application_no'];
                    $_SESSION['student_class'] = $student['class_id'];
                    $_SESSION['student_roll'] = $student['roll_number'];
                    
                    header('Location: student_dashboard.php');
                    exit();
                } else {
                    $error_message = 'গ্রাহক নম্বর খুঁজে পাওয়া যায়নি।';
                }
            } else {
                $error_message = 'গ্রাহক নম্বর বা পাসওয়ার্ড ভুল। ডিফল্ট পাসওয়ার্ড: 123456';
            }
        } catch (Exception $e) {
            $error_message = 'লগইন করতে সমস্যা হয়েছে।';
        }
    } else {
        $error_message = 'গ্রাহক নম্বর এবং পাসওয়ার্ড প্রয়োজন।';
    }
}

?>
<!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-body {
            padding: 30px;
        }
        
        .form-control {
            border-radius: 8px;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
        }
        
        .form-control:focus {
            border-color: #006747;
            box-shadow: 0 0 0 0.25rem rgba(0, 103, 71, 0.25);
        }
        
        .btn-login {
            background: linear-gradient(135deg, #006747 0%, #004d35 100%);
            border: none;
            border-radius: 8px;
            padding: 12px;
            font-weight: 600;
        }
        
        .btn-login:hover {
            background: linear-gradient(135deg, #004d35 0%, #006747 100%);
            transform: translateY(-2px);
        }
    </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"><?php echo $error_message; ?></div>
                        <?php endif; ?>
                        
                        <form method="POST" action="">
                            <div class="mb-3">
                                <label for="customer_number" class="form-label">গ্রাহক নম্বর</label>
                                <input type="text" class="form-control" id="customer_number" name="customer_number" value="<?php echo isset($_POST['customer_number']) ? htmlspecialchars($_POST['customer_number']) : ''; ?>" placeholder="গ্রাহক নম্বর লিখুন" required>
                                <div class="form-text">গ্রাহক নম্বর হিসেবে লগইন করুন</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">ডিফল্ট পাসওয়ার্ড: 123456</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 class="d-grid gap-2">
                                <a href="index.php" class="btn btn-outline-success">
                                    <i class="fas fa-home"></i> হোম পেজ
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>