<?php
// Note: This file assumes $pdo (a PDO database connection object) is available
// from an included file (e.g., config.php or a central database wrapper).

/**
 * Fetches all remembered login devices for a specific user.
 * @param PDO $pdo The database connection object.
 * @param int $user_id The ID of the user.
 * @return array An array of device records.
 */
function getRememberedDevices(PDO $pdo, int $user_id): array
{
    $stmt = $pdo->prepare("
        SELECT id, ip, user_agent, expires_at
        FROM login_devices
        WHERE user_id = :user_id AND expires_at > NOW()
        ORDER BY created_at DESC
    ");
    $stmt->execute(['user_id' => $user_id]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

/**
 * Revokes a specific remembered device by deleting the record.
 * @param PDO $pdo The database connection object.
 * @param int $device_id The ID of the device record to delete.
 * @param int $user_id The ID of the current user (for ownership check).
 * @return bool True on successful deletion, false otherwise.
 */
function revokeDevice(PDO $pdo, int $device_id, int $user_id): bool
{
    $stmt = $pdo->prepare("
        DELETE FROM login_devices
        WHERE id = :id AND user_id = :user_id
    ");
    return $stmt->execute([
        'id' => $device_id,
        'user_id' => $user_id
    ]);
}

/**
 * Changes a user's password and clears all remembered login sessions.
 * @param PDO $pdo The database connection object.
 * @param int $user_id The ID of the user.
 * @param string $new_password The new plaintext password.
 * @return bool True on successful password change, false otherwise.
 */
function changePasswordAndRevokeSessions(PDO $pdo, int $user_id, string $new_password): bool
{
    // 1. Hash the new password
    $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);

    // Start a transaction
    $pdo->beginTransaction();
    
    try {
        // 2. Update the user's password (assuming users table has 'password_hash')
        $stmt_pass = $pdo->prepare("
            UPDATE users SET password_hash = :password_hash WHERE id = :user_id
        ");
        $stmt_pass->execute([
            'password_hash' => $hashed_password,
            'user_id' => $user_id
        ]);
        
        // 3. Revoke all 'remember me' sessions for this user
        $stmt_revoke = $pdo->prepare("
            DELETE FROM login_devices WHERE user_id = :user_id
        ");
        $stmt_revoke->execute(['user_id' => $user_id]);

        // Commit transaction if both succeeded
        $pdo->commit();
        return true;
        
    } catch (Exception $e) {
        // Rollback transaction on failure
        $pdo->rollBack();
        // You might want to log the error here: error_log($e->getMessage());
        return false;
    }
}

// Helper to fetch the user's current password hash for validation
function getUserPasswordHash(PDO $pdo, int $user_id): ?string
{
    $stmt = $pdo->prepare("
        SELECT password_hash FROM users WHERE id = :user_id
    ");
    $stmt->execute(['user_id' => $user_id]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    return $result['password_hash'] ?? null;
}