<?php
// update_db.php
require_once 'config/db.php';

try {
    // 1. Add username column if it doesn't exist
    $pdo->exec("ALTER TABLE `users` ADD COLUMN IF NOT EXISTS `username` VARCHAR(50) UNIQUE AFTER `id` ");
    
    // 2. Set existing users' usernames as their ID for now if empty
    $stmt = $pdo->query("SELECT id, username FROM users WHERE username IS NULL OR username = ''");
    $users = $stmt->fetchAll();
    foreach ($users as $u) {
        $newUsername = 'USER' . str_pad($u['id'], 5, '0', STR_PAD_LEFT);
        $pdo->prepare("UPDATE users SET username = ? WHERE id = ?")->execute([$newUsername, $u['id']]);
    }
    
    // 3. Ensure phone is unique for login
    // First find duplicates and fix if any? (Assuming none for now or just trying to add index)
    // $pdo->exec("ALTER TABLE `users` MODIFY COLUMN `phone` VARCHAR(20) UNIQUE"); // This might fail if duplicates exist

    echo "Database updated successfully.\n";
} catch (PDOException $e) {
    die("Database update failed: " . $e->getMessage());
}
?>
