<?php
// Simple admin setup script
echo "<h2>Quick Admin Setup</h2>";
echo "<style>body{font-family:Arial;margin:20px;} .ok{color:green;} .error{color:red;} .info{color:blue;}</style>";

try {
    // Connect to database
    $pdo = new PDO("mysql:host=localhost;dbname=student_management", "root", "");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Create admins table if it doesn't exist
    $create_table = "
    CREATE TABLE IF NOT EXISTS admins (
        id INT AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(50) UNIQUE NOT NULL,
        password VARCHAR(255) NOT NULL,
        email VARCHAR(100) UNIQUE NOT NULL,
        full_name VARCHAR(100) NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )";
    
    $pdo->exec($create_table);
    echo "<div class='ok'>✓ Admins table created/verified</div>";
    
    // Create default admin user
    $username = 'admin';
    $password = 'admin123';
    $email = 'admin@school.com';
    $full_name = 'System Administrator';
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
    
    // Check if admin exists
    $stmt = $pdo->prepare("SELECT id FROM admins WHERE username = ?");
    $stmt->execute([$username]);
    
    if ($stmt->rowCount() > 0) {
        // Update existing admin
        $stmt = $pdo->prepare("UPDATE admins SET password = ?, email = ?, full_name = ? WHERE username = ?");
        $stmt->execute([$hashed_password, $email, $full_name, $username]);
        echo "<div class='ok'>✓ Admin user updated</div>";
    } else {
        // Create new admin
        $stmt = $pdo->prepare("INSERT INTO admins (username, password, email, full_name) VALUES (?, ?, ?, ?)");
        $stmt->execute([$username, $hashed_password, $email, $full_name]);
        echo "<div class='ok'>✓ Admin user created</div>";
    }
    
    echo "<div class='info'><strong>Login Credentials:</strong><br>";
    echo "Username: <strong>admin</strong><br>";
    echo "Password: <strong>admin123</strong></div>";
    
    echo "<div class='ok'>✓ Setup completed successfully!</div>";
    echo "<p><a href='login.php' style='background:green;color:white;padding:10px;text-decoration:none;border-radius:5px;'>Go to Login Page</a></p>";
    
} catch (PDOException $e) {
    echo "<div class='error'>✗ Error: " . $e->getMessage() . "</div>";
    echo "<p>Make sure:</p>";
    echo "<ul>";
    echo "<li>MySQL is running in XAMPP</li>";
    echo "<li>Database 'student_management' exists</li>";
    echo "<li>Database credentials are correct</li>";
    echo "</ul>";
}
?>
