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

// First, let's check if the student exists without a user account
$stmt = $pdo->prepare("
    SELECT s.* 
    FROM students s 
    LEFT JOIN users u ON s.user_id = u.id 
    WHERE s.first_name = ? AND s.last_name = ? AND u.id IS NULL
");
$stmt->execute(['Alamgir', 'Hossain']);
$student = $stmt->fetch();

if ($student) {
    echo "Found student without user account:\n";
    echo "Name: " . $student['first_name'] . " " . $student['last_name'] . "\n";
    echo "Student ID: " . $student['student_id'] . "\n";
    echo "Email: " . ($student['email'] ?? 'N/A') . "\n";
    
    // Create a username (using student_id)
    $username = $student['student_id'];
    
    // Create a default password (you should change this)
    $password = 'student123';
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
    
    // Use student email or generate one if not available
    $email = $student['email'] ?? $username . '@school.edu';
    
    try {
        // Begin transaction
        $pdo->beginTransaction();
        
        // Create user account
        $user_stmt = $pdo->prepare("
            INSERT INTO users (username, email, password, role, status) 
            VALUES (?, ?, ?, 'student', 'active')
        ");
        $user_stmt->execute([$username, $email, $hashed_password]);
        $user_id = $pdo->lastInsertId();
        
        // Update student record to link to user account
        $student_stmt = $pdo->prepare("
            UPDATE students 
            SET user_id = ? 
            WHERE id = ?
        ");
        $student_stmt->execute([$user_id, $student['id']]);
        
        // Commit transaction
        $pdo->commit();
        
        echo "\nSuccessfully created user account for student!\n";
        echo "Username: " . $username . "\n";
        echo "Password: " . $password . " (Please change this immediately)\n";
        echo "Email: " . $email . "\n";
        
    } catch (Exception $e) {
        $pdo->rollback();
        echo "Error creating user account: " . $e->getMessage() . "\n";
    }
} else {
    echo "No student named 'Alamgir Hossain' found without a user account.\n";
}
?>