<?php
// Migration script: copy rows from `login-t` into `users` and `admins`.
// IMPORTANT: Backup your database before running.
// Assumptions: the old `login-t`.`password` column contains plaintext passwords
// (the previous code compared plaintext). This script will re-hash those
// plaintext values using password_hash(). If your passwords are already
// hashed, DO NOT run this — contact me instead.

require __DIR__ . '/../db_config.php';

echo "Starting migration from `login-t` to `users`/`admins`...\n";

$conn->begin_transaction();
try {
    // note: old table uses `sno` as primary key and does not have user_type column
    $select = $conn->query('SELECT sno, name, password, email, age, phone, gender, dt FROM `login-t`');
    if (!$select) throw new Exception('Failed to read login-t: ' . $conn->error);

    $insertUser = $conn->prepare('INSERT INTO users (username, email, password_hash, age, phone, gender, status, created_at) VALUES (?, ?, ?, ?, ?, ?, "active", ?)');
    if (!$insertUser) throw new Exception('Prepare insert users failed: ' . $conn->error);

    $checkUser = $conn->prepare('SELECT id FROM users WHERE username = ? OR email = ? LIMIT 1');
    if (!$checkUser) throw new Exception('Prepare check users failed: ' . $conn->error);

    $insertAdmin = $conn->prepare('INSERT IGNORE INTO admins (user_id, role_name, created_at) VALUES (?, ?, ?)');
    if (!$insertAdmin) throw new Exception('Prepare insert admins failed: ' . $conn->error);

    $migrated = 0;
    $skipped = 0;
    $promoted = 0;

    while ($row = $select->fetch_assoc()) {
        $oldId = (int)$row['sno'];
        $username = trim($row['name']);
        $email = trim($row['email']);
        $password = $row['password'];
        $age = $row['age'] !== null ? (int)$row['age'] : null;
        $phone = $row['phone'] ?: null;
        $gender = $row['gender'] ?: null;
        // legacy table didn't have explicit user_type column; treat all as 'user' by default
        $user_type = 'user';
        $created_at = $row['dt'] ?: date('Y-m-d H:i:s');

        // Skip if username or email already exists in users
        $checkUser->bind_param('ss', $username, $email);
        $checkUser->execute();
        $cres = $checkUser->get_result();
        if ($cres && $cres->num_rows > 0) {
            $skipped++;
            continue;
        }

        // Hash the stored password (assuming plaintext)
        $pwHash = password_hash($password, PASSWORD_DEFAULT);

        $insertUser->bind_param('sssisss', $username, $email, $pwHash, $age, $phone, $gender, $created_at);
        $ok = $insertUser->execute();
        if (!$ok) {
            throw new Exception('Failed to insert user ' . $username . ': ' . $insertUser->error);
        }
        $newUserId = $conn->insert_id;
        $migrated++;

        // If old user_type says admin, create admins row
        if ($user_type === 'admin') {
            $role = 'admin';
            $insertAdmin->bind_param('iss', $newUserId, $role, $created_at);
            $insertAdmin->execute();
            if ($insertAdmin->affected_rows >= 0) $promoted++;
        }
    }

    $conn->commit();
    echo "Migration complete. Migrated: $migrated, Promoted to admin: $promoted, Skipped (duplicates): $skipped\n";
    exit(0);

} catch (Exception $e) {
    $conn->rollback();
    echo "Migration failed: " . $e->getMessage() . "\n";
    exit(2);
}
